spring注解注入: 詳解


spring注解注入:<context:component-scan>詳解

更多9

spring從2.5版本開始支持注解注入,注解注入可以省去很多的xml配置工作。由於注解是寫入java代碼中的,所以注解注入會失去一定的靈活性,我們要根據需要來選擇是否啟用注解注入。

我們首先看一個注解注入的實際例子,然后再詳細介紹context:component-scan的使用。

如果你已經在用spring mvc的注解配置,那么你一定已經在使用注解注入了,本文不會涉及到spring mvc,我們用一個簡單的例子來說明問題。

本例中我們會定義如下類:

  1. PersonService類,給上層提供Person相關操作
  2. PersonDao類,給PersonService類提供DAO方法
  3. Person類,定義Person相關屬性,是一個POJO
  4. App類,入口類,調用注解注入的PersonService類

PersonService類實現如下:

package cn.outofmemory.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PersonService { @Autowired private PersonDao personDao; public Person getPerson(int id) { return personDao.selectPersonById(id); } }

在Service類上使用了@Service注解修飾,在它的私有字段PersonDao上面有@Autowired注解修飾。@Service告訴spring容器,這是一個Service類,默認情況會自動加載它到spring容器里。而@Autowired注解告訴spring,這個字段是需要自動注入的。

PersonDao類:

package cn.outofmemory.spring; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; @Scope("singleton") @Repository public class PersonDao { public Person selectPersonById(int id) { Person p = new Person(); p.setId(id); p.setName("Person name"); return p; } }

在PersonDao類上面有兩個注解,分別為@Scope和@Repository,前者指定此spring bean的scope是單例,你也可以根據需要將此bean指定為prototype,@Repository注解指定此類是一個容器類,是DA層類的實現。這個類我們只是簡單的定義了一個selectPersonById方法,該方法的實現也是一個假的實現,只是聲明了一個Person的新實例,然后設置了屬性,返回他,在實際應用中DA層的類肯定是要從數據庫或者其他存儲中取數據的。

Person類:

package cn.outofmemory.spring; public class Person { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

Person類是一個POJO。

App類:

package cn.outofmemory.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /**  * Hello spring! from outofmemory.cn  *  */ public class App  {     public static void main( String[] args )     {         ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml");         PersonService service = appContext.getBean(PersonService.class);         Person p = service.getPerson(1);         System.out.println(p.getName());     } }

在App類的main方法中,我們初始化了ApplicationContext,然后從中得到我們注解注入的PersonService類,然后調用此對象的getPerson方法,並輸出返回結果的name屬性。

注解注入也必須在spring的配置文件中做配置,我們看下spring.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.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false"> <context:include-filter type="regex" expression="cn\.outofmemory\.spring\.[^.]+(Dao|Service)"/> </context:component-scan> </beans>

這個配置文件中必須聲明xmlns:context 這個xml命名空間,在schemaLocation中需要指定schema:

           http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.0.xsd

這個文件中beans根節點下只有一個context:component-scan節點,此節點有兩個屬性base-package屬性告訴spring要掃描的包,use-default-filters="false"表示不要使用默認的過濾器,此處的默認過濾器,會掃描包含Service,Component,Repository,Controller注解修飾的類,而此處我們處於示例的目的,故意將use-default-filters屬性設置成了false。

context:component-scan節點允許有兩個子節點<context:include-filter>和<context:exclude-filter>。filter標簽的type和表達式說明如下:

Filter Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example..*Service+ AspectJ語法
regex org\.example\.Default.* Regelar Expression
custom org.example.MyTypeFilter Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter

在我們的示例中,將filter的type設置成了正則表達式,regex,注意在正則里面.表示所有字符,而\.才表示真正的.字符。我們的正則表示以Dao或者Service結束的類。

我們也可以使用annotaion來限定,如下:

<?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.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>  <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>  </context:component-scan> </beans>

 這里我們指定的include-filter的type是annotation,expression則是注解類的全名。

另外context:conponent-scan節點還有<context:exclude-filter>可以用來指定要排除的類,其用法和include-filter一致。

最后我們要看下輸出的結果了,運行App類,輸出:

2014-5-18 21:14:18 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1cac6db: startup date [Sun May 18 21:14:18 CST 2014]; root of context hierarchy 2014-5-18 21:14:18 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [spring.xml] 2014-5-18 21:14:18 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1fcf790: defining beans [personDao,personService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor]; root of factory hierarchy Person name

前幾行都是spring輸出的一些調試信息,最后一行是我們自己程序的輸出。

本文源碼下載:spring-DI-annotation.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM