1. 程式人生 > >Java程式設計師從笨鳥到菜鳥之(七十二)細談Spring(四)利用註解實現spring基本配置詳解

Java程式設計師從笨鳥到菜鳥之(七十二)細談Spring(四)利用註解實現spring基本配置詳解

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               


注:由於本人不大習慣註解方式,所以講解完這裡的註解實現基本配置之後,以後就不再單獨把註解拿出來講解了。


五:Spring註解

1.準備工作
(1)匯入common-annotations.jar


(2)匯入schema檔案 檔名為spring-context-2.5.xsd
(3)xmlbeans節點中配置


2.xml配置工作

 

<?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"
default-default-lazy-init="true">
 <!--將針對註解的處理器配置好  -->    <context:annotation-config />    <!-- 使用annotation定義事務--><tx:annotation-driventransaction-manager="transactionManager" proxy-target-class="true"/> <!--使用annotation 自動註冊bean,並檢查@Required,@Autowired的屬性已被注入base-package為需要掃描的包(含所有子包)--><context:component-scanbase-package="com" /> .....    <beans> 


注:<context:component-scan base-package="*.*" />
 該配置隱式註冊了多個對註解進行解析的處理器,如:
 AutowiredAnnotationBeanPostProcessor     
 CommonAnnotationBeanPostProcessor
 PersistenceAnnotationBeanPostProcessor   
 RequiredAnnotationBeanPostProcessor
 其實,註解本身做不了任何事情,和XML一樣,只起到配置的作用,主要在於背後強大的處理器其中就包括了<context:annotation-config/>配置項裡面的註解所使用的處理器所以配置了<context:component-scanbase-package="">之後,便無需再配置<context:annotation-config>


1.在java程式碼中使用@Autowired@Resource註解方式進行裝配 ,這兩個註解的區別是:@Autowired預設按型別裝配,@Resource預設按名稱裝配,當找不到名稱匹配的bean才會按型別裝配。
@Autowired一般裝配在set方法之上,也可以裝配在屬性上邊,但是在屬性上邊配置,破壞了java的封裝,所以一般不建議使用

@Autowired是根據型別進行自動裝配的。如果當Spring上下文中存在不止一個所要裝配型別的bean時,就會丟擲BeanCreationException異常;如果Spring上下文中不存在所要裝配型別的bean,也會丟擲BeanCreationException異常。我們可以使用@Qualifier配合@Autowired來解決這些問題。

@Autowired  public void setUserDao(@Qualifier("userDao") UserDao userDao) {      this.userDao = userDao;   }  

這樣,Spring會找到iduserDaobean進行裝配。

可能不存在UserDao例項

@Autowired(required = false)   public void setUserDao(UserDao userDao) {       this.userDao = userDao;   }  


2.@ResourceJSR-250標準註解,推薦使用它來代替Spring專有的@Autowired註解)Spring 不但支援自己定義的@Autowired註解,還支援幾個由JSR-250規範定義的註解,它們分別是@Resource@PostConstruct以及@PreDestroy
@Resource的作用相當於@Autowired,只不過@AutowiredbyType自動注入,而@Resource預設按byName自動注入罷了。@Resource有兩個屬性是比較重要的,分別是nametypeSpring@Resource註解的name屬性解析為bean的名字,而type屬性則解析為bean的型別。所以如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不指定name也不指定type屬性,這時將通過反射機制使用byName自動注入策略
@Resource裝配順序

1 如果同時指定了nametype,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則丟擲異常

2 如果指定了name,則從上下文中查詢名稱(id)匹配的bean進行裝配,找不到則丟擲異常

3 如果指定了type,則從上下文中找到型別匹配的唯一bean進行裝配,找不到或者找到多個,都會丟擲異常

4 如果既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配(見2);如果沒有匹配,則回退為一個原始型別(UserDao)進行匹配,如果匹配則自動裝配;


3. @PostConstructJSR-250
在方法上加上註解@PostConstruct,這個方法就會在Bean初始化之後被Spring容器執行(注:Bean初始化包括,例項化Bean,並裝配Bean的屬性(依賴注入))。
它的一個典型的應用場景是,當你需要往Bean裡注入一個其父類中定義的屬性,而你又無法複寫父類的屬性或屬性的setter方法時,如:

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {    private SessionFactory mySessionFacotry;   @Resource  public void setMySessionFacotry(SessionFactory sessionFacotry) {       this.mySessionFacotry = sessionFacotry;      }     @PostConstruct     public void injectSessionFactory() {         super.setSessionFactory(mySessionFacotry);       }   }  



這裡通過@PostConstruct,為UserDaoImpl的父類裡定義的一個sessionFactory私有屬性,注入了我們自己定義的sessionFactory(父類的setSessionFactory方法為final,不可複寫),之後我們就可以通過呼叫super.getSessionFactory()來訪問該屬性了。
4.@PreDestroyJSR-250
在方法上加上註解@PreDestroy,這個方法就會在Bean初始化之後被Spring容器執行。由於我們當前還沒有需要用到它的場景,這裡不不去演示。其用法同@PostConstruct
5.使用Spring註解完成Bean的定義
以上我們介紹了通過@Autowired@Resource來實現在Bean中自動注入的功能,下面我們將介紹如何註解Bean,從而從XML配置檔案中完全移除Bean定義的配置。
@Component需要在對應的類上加上一個@Component註解,就將該類定義為一個Bean了:

@Component  public class UserDaoImpl extends HibernateDaoSupport implements UserDao {       ...   }  

使用@Component註解定義的Bean,預設的名稱(id)是小寫開頭的非限定類名。如這裡定義的Bean名稱就是userDaoImpl。你也可以指定Bean的名稱:
@Component("userDao")
@Component是所有受Spring管理元件的通用形式,Spring還提供了更加細化的註解形式:@Repository@Service@Controller,它們分別對應儲存層Bean,業務層Bean,和展示層Bean。目前版本(2.5)中,這些註解與@Component的語義是一樣的,完全通用,在Spring以後的版本中可能會給它們追加更多的語義。所以,我們推薦使用@Repository@Service@Controller來替代@Component

6.使用<context:component-scan />Bean定義註解工作起來

[html] view plain copy print ?
  1. <code class="language-html"><beans xmlns="http://www.springframework.org/schema/beans"   
  2.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. xmlns:context="http://www.springframework.org/schema/context"        
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans      
  5.  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd    
  6.   http://www.springframework.org/schema/context       
  7. http://www.springframework.org/schema/context/spring-context-2.5.xsd">    
  8.    <context:component-scan base-package="com.bzu" />     
  9. </beans>  </code>  
<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="com.bzu" />   </beans>  



  

這裡,所有通過<bean>元素定義Bean的配置內容已經被移除,僅需要新增一行<context:component-scan />配置就解決所有問題了——Spring XML配置檔案得到了極致的簡化(當然配置元資料還是需要的,只不過以註釋形式存在罷了)。<context:component-scan />base-package屬性指定了需要掃描的類包,類包及其遞迴子包中所有的類都會被處理。
<context:component-scan />還允許定義過濾器將基包下的某些類納入或排除。Spring支援以下4種類型的過濾方式:

· 過濾器型別 表示式範例 說明

· 註解 org.example.SomeAnnotation 將所有使用SomeAnnotation註解的類過濾出來

· 類名指定 org.example.SomeClass 過濾指定的類

· 正則表示式 com\.kedacom\.spring\.annotation\.web\..* 通過正則表示式過濾一些類

· AspectJ表示式 org.example..*Service+ 通過AspectJ表示式過濾一些類

7.使用@Scope來定義Bean的作用範圍
在使用XML定義Bean時,我們可能還需要通過beanscope屬性來定義一個Bean的作用範圍,我們同樣可以通過@Scope註解來完成這項工作:

@Scope("session")   @Component()   public class UserSessionBean implements Serializable {       ...   }  







           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述