Annotation的语法和使用

http://blog.csdn.net/cdl2008sky/article/details/6265742 ide

(1) 、<context:component-scan base-package="*.*" />ui

 该配置隐式注册了多个对注解进行解析的处理器,如:spa

 AutowiredAnnotationBeanPostProcessor      .net

 CommonAnnotationBeanPostProcessor hibernate

 PersistenceAnnotationBeanPostProcessor    prototype

 RequiredAnnotationBeanPostProcessor component

 其实,注解自己作不了任何事情,和XML同样,只起到配置的做用,主要在于背后强大的处理器,其中就包括了<context:annotation-config/>配置项里面的注解所使用的处理器,xml

 因此配置了<context:component-scan base-package="">以后,便无需再配置<context:annotation-config>blog

 

 

(2)、@Component、@Repository、@Service、@Controller、@Autowired、@Resource接口

 而Spring2.5就为咱们引入了组件自动扫描机制 

 它能够在classpath下寻找标注了@Service、@Repository、@Controller、@Component注解的类,并把这些类归入Spring容器中管理,它的做用和在XML中使用bean节点配置组件是同样的使用自动扫描机制,则需配置<context:component-scan base-package="com.jadyer"/>启动自动扫描,其中base-package指定须要扫描的包,它会扫描指定包中的类和子包里面类 

 @Service用于标注业务层组件 

 @Repository用于标注数据访问组件,即DAO组件 

 @Controller用于标注控制层组件,如Struts中的Action 

 @Component泛指组件,当组件不要好归类时,能够使用这个注解进行标注

 一、能够使用诸如@Service("personDao")修改bean名称,而它默认的是将首字母小写的类名做为<bean>名称 

 二、若要更改<bean>做用域的话,能够使用@Scope("prototype")注解来修改<bean>做用域

 

 通常使用@Resource注解,而不要使用@Autowired注解 

 由于@Autowired注解是Spring提供的,而@Resource注解是J2EE提供的 

 在JDK6中就已经包含@Resource注解了,因此它没有跟Spring紧密耦合 

 

 

(3)、<tx:annotation-driven />

 @Transactional 注解能够被应用于接口定义和接口方法、类定义和类的 public 方法上。

 Spring团队的建议是你在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。

 @Service

 @Transactional(rollbackFor=Exception.class)   //对当前类的全部方法起做用

 @SuppressWarnings("serial")

 public class ButtonBo extends GlobalBo {

  ....

  @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) //具体方法上

    public Button findButton(String buttonid) throws BaseException {

     return hibernateEntityDao.get(Button.class, buttonid);

   }

 }

相关文章
相关标签/搜索