Spring provides two ways to define beans and dependencies: XML configuration
and Java annotations
. We can also categorize Spring’s annotations under two groups: DI annotations
and bean annotations
.
Prior to(在前) annotations, we had to manually define all our beans and dependencies in XML configuration files. Now thanks to Spring’s annotations, it can automatically discover and wire all our beans and dependencies for us.
However, we should remember that annotations are useless unless we activate them. In order to activate
them, we can add either <context:annotation-config>
or <context:component-scan>
on top of our XML file.
context:annotation-config
和context:component-scan
组合使用,个人理解 ☞ 他们支持的注解不同,彼此狼狈为奸
<?xml version="1.0" encoding="UTF-8"?>
<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.annotationconfigvscomponentscan.components" />
</beans>
<context:annotation-config>
The <context:annotation-config>
activates the annotations only for the beans already registered in the application context.
The <context:annotation-config>
annotation is mainly used to activate the DI annotations
.
@Autowired, @Qualifier, @Resource, @PostConstruct, @PreDestroy are several ones that
<context:annotation-config>
can detect.
public class AccountService {}
public class UserService {
@Autowired
private AccountService accountService;
}
<bean id="accountService" class="AccountService"></bean>
<bean id="userService" class="UserService"></bean>
#-----------------------------------------------------------------------
# If we didn't use @Autowired, then we would need to set the accountService dependency manually
<bean id="userService" class="UserService">
<property name="accountService" ref="accountService"></property>
</bean>
<context:component-scan>
<context:component-scan>
tells Spring which packages need to be scanned to look for the annotated beans or components
.
@Component, @Repository, @Service, @Controller, @RestController, @Configuration are several ones that
<context:component-scan>
can detect.
@Component
public class UserService {
@Autowired
private AccountService accountService;
}
@Component
public class AccountService {}
参考:
Difference between context:annotation-config vs context:component-scan