天天看點

spring注解Spring注解講解

Spring注解講解

2010-05-15 18:04:50 原文來自: http://hanyexiaoxiao.javaeye.com/blog/410123

使用Spring注解來注入屬性

1.1. 使用注解以前我們是怎樣注入屬性的

類的實作:

Java代碼

public class UserManagerImpl implements UserManager {

    private UserDao userDao;

    public void setUserDao(UserDao userDao) {

        this.userDao = userDao;

    }

    ...

}

public class UserManagerImpl implements UserManager {

        private UserDao userDao;

        public void setUserDao(UserDao userDao) {

                this.userDao = userDao;

        }

        ...

}

配置檔案:

Java代碼

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl">

    <property name="userDao" ref="userDao" />

</bean>

<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">

    <property name="sessionFactory" ref="mySessionFactory" />

</bean>

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl">

        <property name="userDao" ref="userDao" />

</bean>

<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">

        <property name="sessionFactory" ref="mySessionFactory" />

</bean>

1.2. 引入@Autowired注解(不推薦使用,建議使用@Resource)

類的實作(對成員變量進行标注)

Java代碼

public class UserManagerImpl implements UserManager {

    @Autowired

    private UserDao userDao;

    ...

}

public class UserManagerImpl implements UserManager {

        @Autowired

        private UserDao userDao;

        ...

}

或者(對方法進行标注)

Java代碼

public class UserManagerImpl implements UserManager {

    private UserDao userDao;

    @Autowired

    public void setUserDao(UserDao userDao) {

        this.userDao = userDao;

    }

    ...

}

public class UserManagerImpl implements UserManager {

        private UserDao userDao;

        @Autowired

        public void setUserDao(UserDao userDao) {

                this.userDao = userDao;

        }

        ...

}

配置檔案

Java代碼

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl" />

<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">

    <property name="sessionFactory" ref="mySessionFactory" />

</bean>

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl" />

<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">

        <property name="sessionFactory" ref="mySessionFactory" />

</bean>

@Autowired可以對成員變量、方法和構造函數進行标注,來完成自動裝配的工作。以上兩種不同實作方式中,@Autowired的标注位置不同,它們都會在Spring在初始化userManagerImpl這個bean時,自動裝配userDao這個屬性,差別是:第一種實作中,Spring會直接将UserDao類型的唯一一個bean指派給userDao這個成員變量;第二種實作中,Spring會調用setUserDao方法來将UserDao類型的唯一一個bean裝配到userDao這個屬性。

1.3. 讓@Autowired工作起來

要使@Autowired能夠工作,還需要在配置檔案中加入以下代碼

Java代碼

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

1.4. @Qualifier

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

1. 可能存在多個UserDao執行個體

Java代碼

@Autowired

public void setUserDao(@Qualifier("userDao") UserDao userDao) {

    this.userDao = userDao;

}

        @Autowired

        public void setUserDao(@Qualifier("userDao") UserDao userDao) {

                this.userDao = userDao;

        }

這樣,Spring會找到id為userDao的bean進行裝配。

2. 可能不存在UserDao執行個體

Java代碼

@Autowired(required = false)

public void setUserDao(UserDao userDao) {

    this.userDao = userDao;

}

        @Autowired(required = false)

        public void setUserDao(UserDao userDao) {

                this.userDao = userDao;

        }

1.5. @Resource(JSR-250标準注解,推薦使用它來代替Spring專有的@Autowired注解)

Spring 不但支援自己定義的@Autowired注解,還支援幾個由JSR-250規範定義的注解,它們分别是@Resource、@PostConstruct以及@PreDestroy。

@Resource的作用相當于@Autowired,隻不過@Autowired按byType自動注入,而@Resource預設按byName自動注入罷了。@Resource有兩個屬性是比較重要的,分别是name和type,Spring将@Resource注解的name屬性解析為bean的名字,而type屬性則解析為bean的類型。是以如果使用name屬性,則使用byName的自動注入政策,而使用type屬性時則使用byType自動注入政策。如果既不指定name也不指定type屬性,這時将通過反射機制使用byName自動注入政策。

@Resource裝配順序

如果同時指定了name和type,則從Spring上下文中找到唯一比對的bean進行裝配,找不到則抛出異常

如果指定了name,則從上下文中查找名稱(id)比對的bean進行裝配,找不到則抛出異常

如果指定了type,則從上下文中找到類型比對的唯一bean進行裝配,找不到或者找到多個,都會抛出異常

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

1.6. @PostConstruct(JSR-250)

在方法上加上注解@PostConstruct,這個方法就會在Bean初始化之後被Spring容器執行(注:Bean初始化包括,執行個體化Bean,并裝配Bean的屬性(依賴注入))。

它的一個典型的應用場景是,當你需要往Bean裡注入一個其父類中定義的屬性,而你又無法複寫父類的屬性或屬性的setter方法時,如:

Java代碼

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);

    }

    ...

}

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()來通路該屬性了。

1.7. @PreDestroy(JSR-250)

在方法上加上注解@PreDestroy,這個方法就會在Bean初始化之後被Spring容器執行。由于我們目前還沒有需要用到它的場景,這裡不不去示範。其用法同@PostConstruct。

1.8. 使用<context:annotation-config />簡化配置

Spring2.1添加了一個新的context的Schema命名空間,該命名空間對注釋驅動、屬性檔案引入、加載期織入等功能提供了便捷的配置。我們知道注釋本身是不會做任何事情的,它僅提供中繼資料資訊。要使中繼資料資訊真正起作用,必須讓負責處理這些中繼資料的處理器工作起來。

AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor就是處理這些注釋中繼資料的處理器。但是直接在Spring配置檔案中定義這些Bean顯得比較笨拙。Spring為我們提供了一種友善的注冊這些BeanPostProcessor的方式,這就是<context:annotation-config />:

Java代碼

<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:annotation-config />

</beans>

<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:annotation-config />

</beans>

<context:annotationconfig />将隐式地向Spring容器注冊AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor以及RequiredAnnotationBeanPostProcessor這4個BeanPostProcessor。

2. 使用Spring注解完成Bean的定義

以上我們介紹了通過@Autowired或@Resource來實作在Bean中自動注入的功能,下面我們将介紹如何注解Bean,進而從XML配置檔案中完全移除Bean定義的配置。

2.1. @Component(不推薦使用)、@Repository、@Service、@Controller

隻需要在對應的類上加上一個@Component注解,就将該類定義為一個Bean了:

Java代碼

@Component

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

    ...

}

@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。

2.2. 使用<context:component-scan />讓Bean定義注解工作起來

Java代碼

<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.kedacom.ksoa" />

</beans>

<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.kedacom.ksoa" />

</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表達式過濾一些類

以正規表達式為例,我列舉一個應用執行個體:

Java代碼

<context:component-scan base-package="com.casheen.spring.annotation">

    <context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" />

</context:component-scan>

        <context:component-scan base-package="com.casheen.spring.annotation">

                <context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" />

        </context:component-scan>

值得注意的是<context:component-scan />配置項不但啟用了對類包進行掃描以實施注釋驅動Bean定義的功能,同時還啟用了注釋驅動自動注入的功能(即還隐式地在内部注冊了AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),是以當使用<context:component-scan />後,就可以将<context:annotation-config />移除了。

2.3. 使用@Scope來定義Bean的作用範圍

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

Java代碼

@Scope("session")

@Component()

public class UserSessionBean implements Serializable {

    ...

}

@Scope("session")

@Component()

public class UserSessionBean implements Serializable {

        ...

}