现在的位置: 首页 > 综合 > 正文

spring_几个常用注解_bean的配置注入

2017年12月27日 ⁄ 综合 ⁄ 共 2727字 ⁄ 字号 评论关闭

超强链接--spring注解:http://blog.csdn.net/lufeng20/article/details/7598564

---@Autowired,@Qualifier
--区分byType,byName的含义:
如<bean id="office" class="com.baobaotao.Office">
byType:根据class来选择加载,@Autowired
对类成员变量、方法、构造函数进行标注,完成bean自动装配
byName:根据id,name来选择加载,@Qulifier
对成员变量、方法入参、构造函数入参进行注解,指定注入Bean的名称

-@Qualifier只能和@Autowired结合使用,是对@Autowired有益的补充。
例子:
@Autowired
@Qualifier("office")
privateOfficeoffice;

@Autowired
publicvoidsetOffice(@Qualifier("office")Officeoffice){
this.office=office;
}

-@Autowired和@Qualifier结合使用时,自动注入的策略就从byType转变成byName

---使用J2EE的注解
Spring不但支持自己定义的@Autowired的注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource、@PostConstruct以及@PreDestroy
要让JSR-250的注解生效,还需要在Spring容器中注册一个负责处理这些注解的BeanPostProcessor:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>。

--1.@Resource
可以byName,也可以byType,默认是byName。类似与xml配置中的ref。
@Resource的作用类似@Autowired,只不过@Autowired按byType注入,而@Resource默认按byName注入。
@Resource注解类位于Spring发布包的lib/j2ee/common-annotations.jar类包中,因此在使用之前必须将其加入到项目的类库中

---2.
        Spring容器中的Bean是有生命周期的,Spring允许在Bean在初始化完成后以及Bean销毁前执行特定的操作,您既可以通过实现InitializingBean/DisposableBean接口来定制初始化之后/销毁之前的操作方法,也可以通过<bean>元素的init-method/destroy-method属性指定初始化之后/销毁之前调用的操作方法。
JSR-250为初始化之后/销毁之前方法的指定定义了两个注解类,分别是@PostConstruct和@PreDestroy,这两个注解只能应用于方法上。标注了@PostConstruct注解的方法将在类实例化后调用,而标注了@PreDestroy的方法将在类销毁之前调用。

例子:
publicclassBoss{
@Resource
privateCarcar;

@Resource(name="office")
privateOfficeoffice;

@PostConstruct
publicvoidpostConstruct1(){
System.out.println("postConstruct1");
}

@PreDestroy
publicvoidpreDestroy1(){
System.out.println("preDestroy1");
}

}

-使用<context:annotation-config/>简化配置:
<context:annotationconfig/>将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor以及equiredAnnotationBeanPostProcessor这4个BeanPostProcessor。

-使用<context:component-scan/>扫描并注册@Component注解的bean

--通过@Scope指定Bean的作用范围
默认情况下通过@Component定义的Bean都是singleton的
例子:
@Scope("prototype")
@Component("boss")
publicclassBoss{

}

---Spring中除了提供@Component注解外,还定义了几个拥有特殊语义的注解,它们分别是:@Repository、@Service和@Controller。在目前的Spring版本中,这3个注解和@Component是等效的,但是从注解类的命名上,很容易看出这3个注解分别和持久层、业务层和控制层(Web层)相对应。
也就是说目前@Component和@Repository、@Service和@Controller的作用是一样的!

---XML配置bean:
<bean id="boss" class="com.baobaotao.Boss">
<property name="car" ref="car"/>
<property name="office" ref="office"/>
</bean>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="002"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value="红旗CA72"/>
<property name="price" value="2000"/>
</bean>

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

---@SuppressWarnings("unchecked")
取消编译警告

---通过实现ApplicationContextAware接口获取bean
链接;http://www.iteye.com/topic/616752

【上篇】
【下篇】

抱歉!评论已关闭.