Springベース注記Bean依存注入を実現


注記Bean依存注入の実装
概要
     Bean             、           ,    XML    Bean     ,   XML                             。

Spring3       Bean            :
Spring        : Spring           ;
JSR-250  :Java       , Java EE 5    , JDK6         , Spring2.5    。
JSR-330  :Java       ,Java EE 6    ,        JDK  , Spring3    ;
JPA  :                。

         Spring3    ,         ,           Spring           ,           :

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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  

    <context:annotation-config/>  

</beans>  
                  ,       “resources/ chapter12/dependecyInjectWithAnnotation.xml”。

Spring        

一、@Required:依存チェック
     XML        , XML            setter  ,  【3.3.4      】
  @Required          setter    ,      XML     setter  ,                                  ,@Required     setter   ,   XML   setter  ,           :

JAvaコード:
@Requried setterメソッド
1、テストBeanの準備
JAvaコード:
package cn.javass.spring.chapter12;  
public class TestBean {  
    private String message;  
    @Required  
    public void setMessage(String message) {  
        this.message = message;  
    }  
    public String getMessage() {  
        return message;  
    }  
}  


2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean" class="cn.javass.spring.chapter12.TestBean">  
<property name="message" ref="message"/>  
</bean>  
<bean id="message" class="java.lang.String">  
    <constructor-arg index="0" value="hello"/>  
</bean>  

3、          :

java  :

package cn.javass.spring.chapter12;  
//  import 
public class DependencyInjectWithAnnotationTest {  
    private static String configLocation = "classpath:chapter12/dependecyInjectWithAnnotation.xml";  
    private static ApplicationContext ctx = new ClassPathXmlApplicationContext("configLocation");  
    //1、Spring         
     @Test  
    public void testRequiredForXmlSetterInject() {  
        TestBean testBean = ctx.getBean("testBean", TestBean.class);  
        Assert.assertEquals("hello", testBean.getMessage());  
    }  
}  

 XML         setter  ,   Spring            :

java  :

org.springframework.beans.factory.BeanCreationException:  
Error creating bean with name 'testBean' defined in class path resource [chapter12/dependecyInjectWithAnnotation.xml]: Initialization of bean failed;  
nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'message' is required for bean 'testBean'  




** 、@Autowired:    **
    ,      XML       ,  【3.3.3      】。

  @Autowired     ,         ,       、  、    ,      :

java  :

@Autowired(required=true)  
   、  、    

@Autowired               ,      Bean     ,      0 Bean         “required=false”,“required”     @Required  ,  @Required      XML   setter    。

(1)、     :   @Autowired                ,               ,    :

1、    Bean,       @AutoWired  :

java  :

package cn.javass.spring.chapter12;  
import org.springframework.beans.factory.annotation.Autowired;  
public class TestBean11 {  
    private String message;  
    @Autowired //      
    private TestBean11(String message) {  
        this.message = message;  
    }  
    //  message getter setter 
}  


2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean11" class="cn.javass.spring.chapter12.TestBean11"/>  

3、     :

java  :

@Test  
public void testAutowiredForConstructor() {  
    TestBean11 testBean11 = ctx.getBean("testBean11", TestBean11.class);  
    Assert.assertEquals("hello", testBean11.getMessage());  
}  
     Spring        “testBean11”        setter    ,           @ Autowired                。



(2)、    :   @Autowired               。

1、    Bean,      @AutoWired  :

java  :

package cn.javass.spring.chapter12;  
import org.springframework.beans.factory.annotation.Autowired;  
public class TestBean12 {  
    @Autowired //     
    private String message;  
    //  getter setter 
}  


2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean12" class="cn.javass.spring.chapter12.TestBean12"/>  

3、      :

java  :

@Test  
public void testAutowiredForField() {  
    TestBean12 testBean12 = ctx.getBean("testBean12", TestBean12.class);  
    Assert.assertEquals("hello", testBean12.getMessage());  
}  
           XML        ,                。


(3)、      :   @Autowired                。

1、    Bean,      @AutoWired  :

java  :

package cn.javass.spring.chapter12;  
import org.springframework.beans.factory.annotation.Autowired;  
public class TestBean13 {  
    private String message;  
    @Autowired //setter     
    public void setMessage(String message) {  
        this.message = message;  
    }  
    public String getMessage() {  
        return message;  
    }  
}  



java  :

package cn.javass.spring.chapter12;  
//  import 
public class TestBean14 {  
    private String message;  
    private List<String> list;  
    @Autowired(required = true) //              
    private void initMessage(String message, ArrayList<String> list) {  
        this.message = message;  
        this.list = list;  
    }  
    //  getter setter 
}  

2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean13" class="cn.javass.spring.chapter12.TestBean13"/>  
<bean id="testBean14" class="cn.javass.spring.chapter12.TestBean14"/>  
<bean id="list" class="java.util.ArrayList">  
    <constructor-arg index="0">  
        <list>  
            <ref bean="message"/>  
            <ref bean="message"/>  
        </list>  
   </constructor-arg>          
</bean>  

3、      :

java  :

@Test  
public void testAutowiredForMethod() {  
    TestBean13 testBean13 = ctx.getBean("testBean13", TestBean13.class);  
    Assert.assertEquals("hello", testBean13.getMessage());  

    TestBean14 testBean14 = ctx.getBean("testBean14", TestBean14.class);  
    Assert.assertEquals("hello", testBean14.getMessage());  
    Assert.assertEquals(ctx.getBean("list", List.class), testBean14.getList());  
}  


          setter    ,   1             ,   XML      1             ,                。

  “initMessage(String message, ArrayList<String> list)”          ArrayList   List ?    【3.3.3      】            。





 、@Value:  SpEL   ;

    SpEL   ,             ,      :

java  :

@Value(value = "SpEL   ")  
  、  、    

1、            :

java  :

@Value(value = "#{message}")  
private String message;  

2、      @Autowired         :

java  :

@Autowired  
public void initMessage(@Value(value = "#{message}#{message}") String message) {  
    this.message = message;  
}  

3、       @Autowired          :

java  :

@Autowired  
private TestBean43(@Value(value = "#{message}#{message}") String message) {  
    this.message = message;  
}  
          DependencyInjectWithAnnotationTest   testValueInject    。




 、@Qualifier:     ,          ;

@Autowired            ,            Bean   ,            ,       ,  【3.3.3      】          ;

@Qualifier                ,                  ,        :

java  :

@Qualifier(value = "     ")  
  、  、    

(1)、    XML    <qualifier>           ,          :

java  :

<qualifier  type="org.springframework.beans.factory.annotation.Qualifier"  value="     "/>  

  type    ,    ,    Qualifier   ,name   Bean          ,  Bean             <qualifier>,       type           。


1、    Bean:

java  :

package cn.javass.spring.chapter12;  
import javax.sql.DataSource;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Qualifier;  

public class TestBean31 {  
    private DataSource dataSource;  
    @Autowired  
    //  <qualifier>    Bean      
    public void initDataSource(@Qualifier("mysqlDataSource") DataSource dataSource) {  
        this.dataSource = dataSource;  
    }  
    public DataSource getDataSource() {  
        return dataSource;  
    }  
}  

2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean31" class="cn.javass.spring.chapter12.TestBean31"/>  

    @Qualifier("mysqlDataSource")     Bean      ,            <qualifier>       Bean      “mysqlDataSource”:

java  :

<bean id="mysqlDataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
     <qualifier value="mysqlDataSource"/>  
</bean>  

3、      :

java  :

@Test  
public void testQualifierInject1() {  
    TestBean31 testBean31 = ctx.getBean("testBean31", TestBean31.class);  
    try {  
        //  <qualifier>         @Qualifier   
        ctx.getBean("mysqlDataSource");  
        Assert.fail();  
    } catch (Exception e) {  
        //    Bean 
        Assert.assertTrue(e instanceof NoSuchBeanDefinitionException);  
    }  
     Assert.assertEquals(ctx.getBean("mysqlDataSourceBean"), testBean31.getDataSource());  
}  
         <qualifier>             @Qualifier  ,    Bean    , “ctx.getBean("mysqlDataSource")”     Bean 。


(2)、     Bean    :     ,  Bean     <qualifier>         ,        Bean     ,       <qualifier>         。

1、    Bean:

java  :

package cn.javass.spring.chapter12;  
//  import 
public class TestBean32 {  
    private DataSource dataSource;  
    @Autowired  
    @Qualifier(value = "mysqlDataSource2") //  Bean      
    //@Qualifier(value = "mysqlDataSourceBean") 
    //      ,        ,      <qualifier> 
    public void initDataSource(DataSource dataSource) {  
        this.dataSource = dataSource;  
    }  
    public DataSource getDataSource() {  
        return dataSource;  
    }  
}  



2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean32" class="cn.javass.spring.chapter12.TestBean32"/>  
<bean id="oracleDataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource"/>  

3、      :

java  :

@Test  
public void testQualifierInject2() {  
    TestBean32 testBean32 = ctx.getBean("testBean32", TestBean32.class);  
    Assert.assertEquals(ctx.getBean("oracleDataSource"), testBean32.getDataSource());  
}  

     (   <qualifier>  )@Qualifier value     Bean    。


(3)、  @Qualifier       : @Qualifier              ;

                  @Qualifier       。

             ,          ,   Mysql Oracle,                    ,  DAO   SessionFactory ,             ,                     。

1、  @Qualifier            Mysql Oracle   

java  :

package cn.javass.spring.chapter12.qualifier;  
import org.springframework.beans.factory.annotation.Qualifier;  
/**     Mysql   */  
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER})  
@Retention(RetentionPolicy.RUNTIME)  
@Qualifier  
public @interface Mysql {  
}  


java  :

package cn.javass.spring.chapter12.qualifier;  
import org.springframework.beans.factory.annotation.Qualifier;  
/**     Oracle   */  
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER})  
@Retention(RetentionPolicy.RUNTIME)  
@Qualifier  
public @interface Oracle {  
}  


2、    Bean:

java  :

package cn.javass.spring.chapter12;  
//  import 
public class TestBean33 {  
    private DataSource mysqlDataSource;  
    private DataSource oracleDataSource;  
    @Autowired  
    public void initDataSource(@Mysql DataSource mysqlDataSource, @Oracle DataSource oracleDataSource) {  
        this.mysqlDataSource = mysqlDataSource;  
        this.oracleDataSource = oracleDataSource;  
    }  
    public DataSource getMysqlDataSource() {  
        return mysqlDataSource;  
    }  
    public DataSource getOracleDataSource() {  
        return oracleDataSource;  
    }  
}  


3、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean33" class="cn.javass.spring.chapter12.TestBean33"/>  

4、 Spring          :

java  :

<bean id="mysqlDataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
     <qualifier value="mysqlDataSource"/>  
     <qualifier type="cn.javass.spring.chapter12.qualifier.Mysql"/>  
</bean>  
<bean id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
      <qualifier type="cn.javass.spring.chapter12.qualifier.Oracle"/>  
</bean>  

5、      :

java  :

@Test  
public void testQualifierInject3() {  
    TestBean33 testBean33 = ctx.getBean("testBean33", TestBean33.class);  
    Assert.assertEquals(ctx.getBean("mysqlDataSourceBean"), testBean33.getMysqlDataSoruce());  
    Assert.assertEquals(ctx.getBean("oracleDataSource"), testBean33.getOracleDataSoruce());  
}  

      ,       @Qualifier             。


            ,             :

1、         :

java  :

package cn.javass.spring.chapter12.qualifier;  
public enum DataBase {  
    ORACLE, MYSQL;  
}  

2、    @Qualifier       

java  :

package cn.javass.spring.chapter12.qualifier;  
//  import 
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER})  
@Retention(RetentionPolicy.RUNTIME)  
@Qualifier  
public @interface DataSourceType {  
    String ip();      //  ip,         
    DataBase database();//        
}  

3、    Bean:

java  :

package cn.javass.spring.chapter12;  
import javax.sql.DataSource;  
import org.springframework.beans.factory.annotation.Autowired;  
import cn.javass.spring.chapter12.qualifier.DataBase;  
import cn.javass.spring.chapter12.qualifier.DataSourceType;  
public class TestBean34 {  
    private DataSource mysqlDataSource;  
    private DataSource oracleDataSource;  
    @Autowired  
    public void initDataSource(  
            @DataSourceType(ip="localhost", database=DataBase.MYSQL)  
            DataSource mysqlDataSource,  
            @DataSourceType(ip="localhost", database=DataBase.ORACLE)  
            DataSource oracleDataSource) {  
        this.mysqlDataSource = mysqlDataSource;  
        this.oracleDataSource = oracleDataSource;  
    }  
      //  getter   
}  

4、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean34" class="cn.javass.spring.chapter12.TestBean34"/>  

5、 Spring          :

java  :

<bean id="mysqlDataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    <qualifier value="mysqlDataSource"/>  
    <qualifier type="cn.javass.spring.chapter12.qualifier.Mysql"/>  
    <qualifier type="cn.javass.spring.chapter12.qualifier.DataSourceType">  
        <attribute key="ip" value="localhost"/>  
        <attribute key="database" value="MYSQL"/>  
    </qualifier>  
</bean>  
<bean id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    <qualifier type="cn.javass.spring.chapter12.qualifier.Oracle"/>  
    <qualifier type="cn.javass.spring.chapter12.qualifier.DataSourceType">  
        <attribute key="ip" value="localhost"/>  
        <attribute key="database" value="ORACLE"/>  
    </qualifier>  
</bean>  

6、      :

java  :

@Test  
public void testQualifierInject3() {  
    TestBean34 testBean34 = ctx.getBean("testBean34", TestBean34.class);  
    Assert.assertEquals(ctx.getBean("mysqlDataSourceBean"), testBean34.getMysqlDataSource());  
    Assert.assertEquals(ctx.getBean("oracleDataSource"), testBean34.getOracleDataSoruce());  
}  
        ,       @Qualifier             。



 、          :     @Qualifier,               ;

1、                      :

java  :

package cn.javass.spring.chapter12.qualifier;  
//  import 
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER})  
@Retention(RetentionPolicy.RUNTIME)  
public @interface CustomQualifier {  
    String value();  
}  


2、    Bean:

java  :

package cn.javass.spring.chapter12;  
//  import 
public class TestBean35 {  
    private DataSource dataSoruce;  
    @Autowired  
    public TestBean35(@CustomQualifier("oracleDataSource") DataSource dataSource) {  
        this.dataSoruce = dataSource;  
    }  
    public DataSource getDataSoruce() {  
        return dataSoruce;  
    }  
}  

3、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean35" class="cn.javass.spring.chapter12.TestBean35"/>  

4、   Spring       CustomQualifier          ,     Spring    :

java  :

<bean id="customAutowireConfigurer" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">  
    <property name="customQualifierTypes">  
        <set>  
            <value>cn.javass.spring.chapter12.qualifier.CustomQualifier</value>  
        </set>  
   </property>  
</bean>  

5、      :

java  :

@Test  
public void testQualifierInject5() {  
    TestBean35 testBean35 = ctx.getBean("testBean35", TestBean35.class);  
    Assert.assertEquals(ctx.getBean("oracleDataSource"), testBean35.getDataSource());  
}  
           ,     Spring        ,              Spring   Qualifier  。

               ,           :
      Bean         ;
  Bean               ;
    、  、            ,               Bean。




12.2.3  JSR-250  
 、@Resource:    ,        ,    name         ,           :

java  :

@Resource(name = "   ")  
   setter    

1、    Bean:

java  :

package cn.javass.spring.chapter12;  
import javax.annotation.Resource;  
public class TestBean41 {  
    @Resource(name = "message")  
    private String message;  
    //  getter setter 
}  


2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean41" class="cn.javass.spring.chapter12.TestBean41"/>  

3、      : 

java  :

@Test  
public void testResourceInject1() {  
    TestBean41 testBean41 = ctx.getBean("testBean41", TestBean41.class);  
    Assert.assertEquals("hello", testBean41.getMessage());  
}  
          , @Autowired        name       。

      @Resource        :
@Resource       setter    ,     @Autowired       ;
@Resource     name           setter            ,            ;
@Resource    JNDI       ,         Spring     ,    JNDI     Spring            。


 、@PostConstruct PreDestroy:                ;

1、    TestBean41       :

java  :

@PostConstruct  
public void init() {  
    System.out.println("==========init");  
}  
@PreDestroy  
public void destroy() {  
    System.out.println("==========destroy");  
}  

2、        :

java  :

@Test  
public void resourceInjectTest1() {  
    ((ClassPathXmlApplicationContext) ctx).registerShutdownHook();  
    TestBean41 testBean41 = ctx.getBean("testBean41", TestBean41.class);  
    Assert.assertEquals("hello", testBean41.getMessage());  
}  
         <bean>   init-method destroy-method             ,        ,                  。


12.2.4  JSR-330  
         JSR-330      jar , spring-framework-3.0.5.RELEASE-dependencies.zip     jar     :

com.springsource.javax.inject-1.0.0.jar

        、@Inject:      @Autowired,    required  ;
        、@Named:  Bean  ,   Spring  @Qualifier       Bean      ;
        、@Qualifier:    Spring  @Qualifier    @Qualifier       ,       ,  value1、    @Qualifier          Mysql   

java  :

package cn.javass.spring.chapter12.qualifier;  
//    import 
import javax.inject.Qualifier;  
@Target({ElementType.FIELD, ElementType.PARAMETER})  
@Retention(RetentionPolicy.RUNTIME)  
@Qualifier  
public @interface JSR330Mysql {  
}  



2、    Bean:


java  :

package cn.javass.spring.chapter12;  
import javax.inject.Inject;  
import javax.inject.Named;  
import javax.sql.DataSource;  
import cn.javass.spring.chapter12.qualifier.JSR330Mysql;  
public class TestBean51 {  
    private DataSource mysqlDataSource;  
    private DataSource oracleDataSource;  
    @Inject  
    public void initDataSoruce(  
            @JSR330Mysql  DataSource mysqlDataSource,  
            @Named("oracleDataSource") DataSource oracleDataSource) {  
        this.mysqlDataSource = mysqlDataSource;  
        this.oracleDataSource = oracleDataSource;  

    }  
    //  getter 
}  

3、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<bean id="testBean51" class="cn.javass.spring.chapter12.TestBean51"/>  

4、 Spring     mysqlDataSourceBean   :

java  :

<bean id="mysqlDataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
         <qualifier value="mysqlDataSource"/>  
         <qualifier type="cn.javass.spring.chapter12.qualifier.Mysql"/>  
         <qualifier type="cn.javass.spring.chapter12.qualifier.DataSourceType">  
             <attribute key="ip" value="localhost"/>  
             <attribute key="database" value="MYSQL"/>  
         </qualifier>  
         <qualifier type="cn.javass.spring.chapter12.qualifier.JSR330Mysql"/>  
</bean>  


5、      :

java  :

@Test  
public void testInject() {  
    TestBean51 testBean51 = ctx.getBean("testBean51", TestBean51.class);  
    Assert.assertEquals(ctx.getBean("mysqlDataSourceBean"), testBean51.getMysqlDataSource());  
    Assert.assertEquals(ctx.getBean("oracleDataSource"), testBean51.getOracleDataSource());  
}  


      ,  JSR-330        。

        JSR-330   Spring                :
Spring   @Autowired        JSR-330 @Inject  ;
Spring   @Qualifier      Bean         JSR-330 @Named  ;
Spring   @Qualifier   @Qualifier            JSR-330 @Qualifier  。



12.2.5  JPA  
    EntityManagerFactory EntityManager。

1、    Bean:

java  :

package cn.javass.spring.chapter12;  
//  import 
public class TestBean61 {  
    @PersistenceContext(unitName = "entityManagerFactory")  
    private EntityManager entityManager;  

    @PersistenceUnit(unitName = "entityManagerFactory")  
    private EntityManagerFactory entityManagerFactory;  

    public EntityManager getEntityManager() {  
        return entityManager;  
    }  
    public EntityManagerFactory getEntityManagerFactory() {  
        return entityManagerFactory;  
    }  
}  

2、 Spring    (chapter12/dependecyInjectWithAnnotation.xml)    Bean  :

java  :

<import resource="classpath:chapter7/applicationContext-resources.xml"/>  
<import resource="classpath:chapter8/applicationContext-jpa.xml"/>  
<bean id="testBean61" class="cn.javass.spring.chapter12.TestBean61"/>  
                     ,           。


3、      :

java  :


@Test  
public void testJpaInject() {  
    TestBean61 testBean61 = ctx.getBean("testBean61", TestBean61.class);  
    Assert.assertNotNull(testBean61.getEntityManager());  
    Assert.assertNotNull(testBean61.getEntityManagerFactory());  
}  

          ,  JPA        。

JPA     @Resource        unitName   JNDI     ,       Spring     。