Javaweb Spring几个基本注释

时间:2015-08-01 02:04:40   收藏:0   阅读:249

<div class="iteye-blog-content-contain" style="font-size: 14px"></div>

?一、@Autowired注解:

? ? ?如要仅仅使用此注解,需要在spring容器中声明该注解的解析Bean:
? ? ? ? ??
? ?? ?????<bean class="org.springframework.beans.factory.annotation. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?AutowiredAnnotationBeanPostProcessor"/>
?
? ? ?该bean会自动扫描spring中所有autowired注解,默认是类型匹配。
? ? ?当所自动注入的bean超过1个,或者没有时,都会报BeanCreationException
? ? ?该注解可以用在变量上面,方法,构造方法上面,对方法传入的参数进行注入
?
二、@Qualifier注解:
? ? ?该注解制定autowired注入bean的名称,所以它是对变量注释的:
? ? ?
?????@Autowired ??
?????public Boss(Car car , @Qualifier("office")Office office){
? ??? ? ?//方法体
?????};
?
? ? ?
?????@Autowired ??
?????@Qualifier("office") ??
?????private Office office;
?
三、@Resource
? ? ?作用和@Autowired 一样,但是它默认是根据类型来注入,也可更改为type,在lib/j2ee/common-annotations.jar包中,在xml文件中声明:
? ? ?
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
?
四、@preConstruct ?@preDistory
? ? ?这两个注释是在bean实例化和销毁前执行的方法注释,也就是说,注释在方法上面。这两个注释的功能,也可以通过<bean>元素的 init-method/destory-method来配置
?
?
五、<context : annotation-config/>简化配置
? ? ?在xml文件中配置这句话,就不需要一一引入每种注释的处理类了
? ? ?spring 2.x 中对context引入了一个新的Schema 命名空间, 该命名空间对注释驱动,属性文件引入,加载期织入等功能提供了便捷的配置,也就是免去了配置每个注释的处理类,默认会注册:AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessorPersistenceAnnotationBeanPostProcessor?以及equiredAnnotationBeanPostProcessor?这 4 个 BeanPostProcessor。
在配置文件中使用 context 命名空间之前,必须在 <beans> 元素中声明 context 命名空间。
?
————————————————————可以把类定义成bean的注解-------------------------------------------------------------
六、@Component
? ? ?在spring2.5中提供该注释,可以直接定义bean,它是个泛泛的概念,可以定义在任何层次(dao、service、controller...)上
?
七、@Repository
? ? ?只能定义在Dao层,因为该注解不仅仅是将类识别为bean,而且还能将类所抛出的数据访问异常封装成为spring的数据访问异常,使得异常独立于底层框架
?
八、@Service
? ? ?标注在业务层上
?
?
九、@Controller
? ? ?标注在控制层,@Controller(“name”) ?@Controller(value=“name”)意思是告诉spring注册bean的时候,把bean名字设为name
?
?
十、@Scope(“singleton”||”prototype")
? ? ?该注释是告诉该类在创建bean的时候,是以单例模式,还是每次都重新创建,默认单例。
? ? ?可以避免struts里面线程安全问题
?
使用这几个注解,spring会自动创建相应的bean并注册到applicationContext中,默认都是sigleton模式
?
?
<context : component-scan base-package=“”> 扫描子包中上面四个注释,然后注册成bean,该语句会默认引入AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor,所以可以不用
<context : annotation-config/>
------------------------------------------------------------------------------------------------------------------------------------------------------------
?
?
xml方式和注释方式使用挑选各自优缺:
? ? ?1、注释是在Java源码上面,如果需要在某个地方加入bean,那就需要调整Java源码,然后重新编译,而XML直接修改就可以了
? ? ?2、如果bean不是自己写的类,而是Java里面的,那么注释就没法用了。
? ? ?3、注释配置往往是类级别的,而 XML 配置则可以表现得更加灵活。比如相比于?@Transaction?事务注释,使用 aop/tx 命名空间的事务配置更加灵活和简单。
?
?

原文:http://we-are-here.iteye.com/blog/2231858

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!