天天看點

Spring Annotation 詳解

(1) 、<context:component-scan base-package="*.*" /> 該配置隐式注冊了多個對注解進行解析的處理器,如:
 AutowiredAnnotationBeanPostProcessor      
 CommonAnnotationBeanPostProcessor 
 PersistenceAnnotationBeanPostProcessor    
 RequiredAnnotationBeanPostProcessor 
 其實,注解本身做不了任何事情,和XML一樣,隻起到配置的作用,主要在于背後強大的處理器 
 其中就包括了<context:annotation-config/>配置項裡面的注解所使用的處理器 
 是以配置了<context:component-scan base-package="">之後,便無需再配置<context:annotation-config>(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泛指元件,當元件不要好歸類時,可以使用這個注解進行标注
 1、可以使用諸如@Service("personDao")修改bean名稱,而它預設的是将首字母小寫的類名作為<bean>名稱 
 2、若要更改<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);
   }
 }