在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;
本文深入探讨了Spring框架中基于注解的配置方法,包括@Bean、@Component、@Repository、@Service、@Controller等注解的使用,以及如何通过@ComponentScan进行组件扫描。此外,还详细介绍了@Autowired、@Qualifier、@Lazy等注解在自动装配Bean中的应用,以及@Scope、@PostConstruct、@PreDestroy在Bean作用范围和生命周期管理中的作用。
307

被折叠的 条评论
为什么被折叠?



