Spring常用註解,自動掃描裝配Bean

1 引入context命名空間(在Spring的配置文件中),配置文件如下:

xmlns:context="http://www.springframework.org/schema/context"  
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd 

打開配置 <context:component-scan base-package="包名(掃描本包及子包)"/>

spring 會自動掃描cn.pic包下面有註解的類,完成Bean的裝配。

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:context="http://www.springframework.org/schema/context"         
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
           
          <context:component-scan base-package="cn.pic"/>  
</beans>   

2 在classPath中加入註解用的jar包

lib\j2ee\common-annotations.jar

Spring 的context:component-scan掃描支持掃描jar包的方法:

eclipse自帶的jar打包程序,默認打包的時候有個選項<Add directory entries>沒有勾選,只要勾選了,就可以了.

-----------常用註解--------

 

--定義Bean的註解

 

@Controller

@Controller("Bean的名稱")

定義控制層Bean,如Action

 

@Service          

@Service("Bean的名稱")

定義業務層Bean

 

@Repository   

@Repository("Bean的名稱")

定義DAO層Bean

 

@Component  

定義Bean, 不好歸類時使用.

 

--自動裝配Bean (選用一種註解就可以)

@Autowired  (Srping提供的)

默認按類型匹配,自動裝配(Srping提供的),可以寫在成員屬性上,或寫在setter方法上

 

@Autowired(required=true)  

一定要找到匹配的Bean,否則拋異常。 默認值就是true 

 

@Autowired

@Qualifier("bean的名字") 

按名稱裝配Bean,與@Autowired組合使用,解決按類型匹配找到多個Bean問題。

 

@Resource   JSR-250提供的

默認按名稱裝配,當找不到名稱匹配的bean再按類型裝配.

可以寫在成員屬性上,或寫在setter方法上

可以通過@Resource(name="beanName") 指定被注入的bean的名稱, 要是未指定name屬性, 默認使用成員屬性的變量名,一般不用寫name屬性.

@Resource(name="beanName")指定了name屬性,按名稱注入但沒找到bean, 就不會再按類型裝配了.

 

@Inject   是JSR-330提供的

按類型裝配,功能比@Autowired少,沒有使用的必要。

 

--定義Bean的作用域和生命過程

@Scope("prototype")

值有:singleton,prototype,session,request,session,globalSession

 

@PostConstruct 

相當於init-method,使用在方法上,當Bean初始化時執行。

 

@PreDestroy 

相當於destory-method,使用在方法上,當Bean銷燬時執行。

 

--聲明式事務

@Transactional  




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章