BAEL-2850: Difference between <context:annotation-config> vs (#7249)

<context:component-scan>
This commit is contained in:
codehunter34 2019-07-06 12:41:48 -04:00 committed by maibin
parent 2913643e81
commit 88586cc09f
4 changed files with 62 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package com.baeldung.components;
import org.springframework.stereotype.Component;
@Component
public class AccountService {
}

View File

@ -0,0 +1,16 @@
package com.baeldung.components;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserService {
@Autowired
private AccountService accountService;
public AccountService getAccountService() {
return accountService;
}
}

View File

@ -0,0 +1,15 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<context:component-scan base-package="com.baeldung.components" />
<bean id="accountService" class="com.baeldung.components.AccountService"></bean>
<bean id="userService" class="com.baeldung.components.UserService">
<!-- If we have <context:annotation-config/> on top, then we don't need to set the properties(dependencies) in XML. -->
<!-- <property name="accountService" ref="accountService"></property> -->
</bean>
</beans>

View File

@ -0,0 +1,23 @@
package com.baeldung;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.components.AccountService;
import com.baeldung.components.UserService;
public class SpringXMLConfigurationIntegrationTest {
@Test
public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
UserService userService = context.getBean(UserService.class);
AccountService accountService = context.getBean(AccountService.class);
Assert.assertNotNull(userService);
Assert.assertNotNull(accountService);
Assert.assertNotNull(userService.getAccountService());
}
}