在IOC容器中装配Bean——基于注解的配置
一、使用注解定义Bean
@Component("userDao")
public class UserDao{
...
}
此处@Component
注解等效于:
<bean id="userDao" class="com.hef.UserDao"/>
除了@Component
,Spring还提供了3个功能基本和@Component
等效的注解,分别对应域DAO、Service、及Web层的Controller进行注解:
@Repository
用于对Dao实现类进行标注;
@Service
用于Service实现类进行标注;
@Controller
用于Controller实现类进行标注;
二、扫描定义的Bean
xmlns:context="http://www.springframework.org/schema/context"
....
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
....
<context:component-scan base-package="com.hef.dao" resource-pattern=""/>
resource-pattern
属性,过滤出特定的类;
还可以使用context:exclude-filter
和context:include-filter
<context:component-scan base-package="com.hef.dao">
<context:exclude-filter type="" expression=""/>
<context:include-filter type="" expression=""/>
</context:component-scan>
三、自动装配Bean
3.1 通过@Autowired
进行自动装配
@Autowired
默认按类型(byType)匹配的方式在容器中查找匹配的Bean;
3.2 required
属性
@Autowired(required=false)
,在Spring找不到匹配的Bean时,不要抛出异常。
3.3 @Qualifier
指定注入Bean的名称
如果容器中有一个以上的Bean时,可以通过@Qualifier
注解限定Bean的名称。
3.4 @Autowired
可以对类成员变量及方法对入参进行标注
默认情况下,Spring将自动选择匹配入参类型的Bean进行注入。Spring允许对方法入参标注@Qualifier
一指定注入Bean的名称。
在项目中建议在方法上标注@Autowied
标注,这样更面向对象。
3.5 对集合进行标注
// Spring会将容器中所有类型为Plugin的Bean注入这个变量中
@Autowired(required=false)
private List<Plugin> plugins;
// 将Plugin类型的Bean注入Map中,key是bean的名字,value是所有实现了Plugin的Bean
@Autowired(required=false)
private Map<String,Plugin> pluginMaps;
3.6 @Lazy
对延迟依赖注入的支持
注意,@Lazy
注解必须同时标注在属性及目标Bean上,二者缺一,则延迟注入无效。
3.7 对标准注解的支持@Resource
、@Inject
@Resource
注解要求提供一个Bean名称的属性,如果属性为空,则自动采用标注处的变量名或方法名作用Bean的名称;
@Inject
同样是按照类型匹配注入Bean的,只不过它没有required
属性。
四、Bean作用范围及生命过程方法
4.1 通过@Scope
指定Bean的作用范围
4.2 @PostConstruct
和 @PreDestory
@PostConstruct
相当于init-method
;
@PreDestory
相当于destory-method
;