@Component :把普通pojo实例化到spring容器中,相当于配置文件中的 。
<bean id="" class=""/>
@ComponentScan(basePackages = {"",""}):启用组件扫描,如果没有其它配置的话(@ComponentScan),默认会扫描与配置类相同的 包,比如,扫描的时候查找带有@Component注解的类,并在Spring中自动为其创建一个bean。对应的xml为:
<context:component-scan base-package="chapter4"></context:component-scan>
@Configuration:与xml配置文件等效,看下面例子。
@Configuration
@ComponentScan
public class chapter4Config {
@Bean
public Audience audience()
{
return new Audience();
}
}
相当于以下的xml
<?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:component-scan base-package="chapter4"></context:component-scan>
<bean id="audience" class="chapter4.Audience"></bean>
</beans>
@Qualifier具体用法:
@Autowired注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException 异常,并指出必须至少拥有一个匹配的 Bean。@Autowired 默认是按照byType进行注入的,如果发现找到多个bean,则,又按照byName方式比对,如果还有多个,则报出异常。@Autowired可以手动指定按照byName方式注入,使用@Qualifier标签。用法如下代码:
@Autowired
@Qualifier("article")
Performance performance1;
@Autowired
@Qualifier("musician")
Performance performance2;
//Article与Musician类都实现了Performance,Article与Musician都注入到了Spring容器中