【第十二章】零配置 之 12.3 注解实现Bean定义、12.4基于Java类定义Bean配置元数据 ——跟我学spring3

12.3  注解实现Bean定义

12.3.1  概述

前边介绍的Bean定义全是基于XML方式定义配置元数据,且在【12.2注解实现Bean依赖注入】一节中介绍了通过注解来减少配置数量,但并没有完全消除在XML配置文件中的Bean定义,因此有没有方式完全消除XML配置Bean定义呢?

 

Spring提供通过扫描类路径中的特殊注解类来自动注册Bean定义。同注解驱动事务一样需要开启自动扫描并注册Bean定义支持,使用方式如下(resources/chapter12/ componentDefinitionWithAnnotation.xml):

 

java代码:
Java代码 复制代码  收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns:aop="http://www.springframework.org/schema/aop"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="   
  6.        http://www.springframework.org/schema/beans  
  7.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.        http://www.springframework.org/schema/aop  
  9.        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.        http://www.springframework.org/schema/context  
  11.        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  12.   
  13.     <aop:aspectj-autoproxy />   
  14.   
  15.     <context:component-scan base-package="cn.javass.spring.chapter12"/>   
  16.   
  17. </beans>  
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <aop:aspectj-autoproxy />

    <context:component-scan base-package="cn.javass.spring.chapter12"/>

</beans>

 

       使用<context:component-scan>标签来表示需要要自动注册Bean定义,而通过base-package属性指定扫描的类路径位置。

       <context:component-scan>标签将自动开启“注解实现Bean依赖注入”支持。

       此处我们还通过<aop:aspectj-autoproxy/>用于开启Spring对@AspectJ风格切面的支持。

 

Spring基于注解实现Bean定义支持如下三种注解:

  • Spring自带的@Component注解及扩展@Repository、@Service、@Controller,如图12-1所示;
  • JSR-250 1.1版本中中定义的@ManagedBean注解,是Java EE 6标准规范之一,不包括在JDK中,需要在应用服务器环境使用(如Jboss),如图12-2所示;
  • JSR-330的@Named注解,如图12-3所示。

 

图12-1 Spring自带的@Component注解及扩展

 

 

图12-2 JSR-250中定义的@ManagedBean注解及自定义扩展

 

 

图12-3 JSR-330的@Named注解及自定义扩展

 

图12-2和图12-3中的自定义扩展部分是为了配合Spring自带的模式注解扩展自定义的,并不包含在Java EE 6规范中,在Java EE 6中相应的服务层、DAO层功能由EJB来完成。

 

在Java EE中有些注解运行放置在多个地方,如@Named允许放置在类型、字段、方法参数上等,因此一般情况下放置在类型上表示定义,放置在参数、方法等上边一般代表使用(如依赖注入等等)。

 

 

12.3.2  Spring自带的@Component注解及扩展

一、@Component:定义Spring管理Bean,使用方式如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Component("标识符")   
  2. POJO类  
@Component("标识符")
POJO类

  在类上使用@Component注解,表示该类定义为Spring管理Bean,使用默认value(可选)属性表示Bean标识符。

 

1、定义测试Bean类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12;   
  2. import org.springframework.beans.factory.annotation.Autowired;   
  3. import org.springframework.context.ApplicationContext;   
  4. import org.springframework.stereotype.Component;   
  5. @Component("component")   
  6. public class TestCompoment {   
  7.     @Autowired  
  8.     private ApplicationContext ctx;   
  9.     public ApplicationContext getCtx() {   
  10.         return ctx;   
  11.     }   
  12. }  
package cn.javass.spring.chapter12;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component("component")
public class TestCompoment {
    @Autowired
    private ApplicationContext ctx;
    public ApplicationContext getCtx() {
        return ctx;
    }
}

 


2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

 

3、定义测试类和测试方法:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12;   
  2. //省略import   
  3. public class ComponentDefinitionWithAnnotationTest {   
  4.     private static String configLocation = "classpath:chapter12/componentDefinitionWithAnnotation.xml";   
  5.     private static ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);   
  6.     @Test  
  7.     public void testComponent() {   
  8.         TestCompoment component = ctx.getBean("component", TestCompoment.class);   
  9.         Assert.assertNotNull(component.getCtx());   
  10.     }   
  11. }  
package cn.javass.spring.chapter12;
//省略import
public class ComponentDefinitionWithAnnotationTest {
    private static String configLocation = "classpath:chapter12/componentDefinitionWithAnnotation.xml";
    private static ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);
    @Test
    public void testComponent() {
        TestCompoment component = ctx.getBean("component", TestCompoment.class);
        Assert.assertNotNull(component.getCtx());
    }
}

    测试成功说明被@Component注解的POJO类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配。

 

@AspectJ风格的切面可以通过@Compenent注解标识其为Spring管理Bean,而@Aspect注解不能被Spring自动识别并注册为Bean,必须通过@Component注解来完成,示例如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.aop;   
  2. //省略import   
  3. @Component  
  4. @Aspect  
  5. public class TestAspect {   
  6.     @Pointcut(value="execution(* *(..))")   
  7.     private void pointcut() {}   
  8.     @Before(value="pointcut()")   
  9.     public void before() {   
  10.         System.out.println("=======before");   
  11.     }   
  12. }  
package cn.javass.spring.chapter12.aop;
//省略import
@Component
@Aspect
public class TestAspect {
    @Pointcut(value="execution(* *(..))")
    private void pointcut() {}
    @Before(value="pointcut()")
    public void before() {
        System.out.println("=======before");
    }
}

 

 

通过@Component将切面定义为Spring管理Bean。

 

 

二、@Repository:@Component扩展,被@Repository注解的POJO类表示DAO层实现,从而见到该注解就想到DAO层实现,使用方式和@Component相同;

      

1、定义测试Bean类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.dao.hibernate;   
  2. import org.springframework.stereotype.Repository;   
  3. @Repository("testHibernateDao")   
  4. public class TestHibernateDaoImpl {   
  5.     
  6. }  
package cn.javass.spring.chapter12.dao.hibernate;
import org.springframework.stereotype.Repository;
@Repository("testHibernateDao")
public class TestHibernateDaoImpl {
 
}

 

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

 

3、定义测试方法:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testDao() {   
  3. TestHibernateDaoImpl dao =   
  4. ctx.getBean("testHibernateDao", TestHibernateDaoImpl.class);   
  5. Assert.assertNotNull(dao);   
  6. }  
@Test
public void testDao() {
TestHibernateDaoImpl dao =
ctx.getBean("testHibernateDao", TestHibernateDaoImpl.class);
Assert.assertNotNull(dao);
}

    测试成功说明被@Repository注解的POJO类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配,并且被@Repository注解的类表示DAO层实现。

 

 

三、@Service:@Component扩展,被@Service注解的POJO类表示Service层实现,从而见到该注解就想到Service层实现,使用方式和@Component相同;

 

1、定义测试Bean类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.service.impl;   
  2. import org.springframework.beans.factory.annotation.Autowired;   
  3. import org.springframework.beans.factory.annotation.Qualifier;   
  4. import org.springframework.stereotype.Service;   
  5. import cn.javass.spring.chapter12.dao.hibernate.TestHibernateDaoImpl;   
  6. @Service("testService")   
  7. public class TestServiceImpl {   
  8.     @Autowired  
  9.     @Qualifier("testHibernateDao")   
  10.     private TestHibernateDaoImpl dao;   
  11.     public TestHibernateDaoImpl getDao() {   
  12.         return dao;   
  13.     }   
  14. }  
package cn.javass.spring.chapter12.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import cn.javass.spring.chapter12.dao.hibernate.TestHibernateDaoImpl;
@Service("testService")
public class TestServiceImpl {
    @Autowired
    @Qualifier("testHibernateDao")
    private TestHibernateDaoImpl dao;
    public TestHibernateDaoImpl getDao() {
        return dao;
    }
}

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

 

 

3、定义测试方法:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testService() {   
  3.     TestServiceImpl service = ctx.getBean("testService", TestServiceImpl.class);   
  4.     Assert.assertNotNull(service.getDao());   
  5. }  
@Test
public void testService() {
    TestServiceImpl service = ctx.getBean("testService", TestServiceImpl.class);
    Assert.assertNotNull(service.getDao());
}

 

测试成功说明被@Service注解的POJO类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配,并且被@Service注解的类表示Service层实现。

 

 

四、@Controller:@Component扩展,被@Controller注解的类表示Web层实现,从而见到该注解就想到Web层实现,使用方式和@Component相同;

 

1、定义测试Bean类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.action;   
  2. //省略import   
  3. @Controller  
  4. public class TestAction {   
  5.     @Autowired  
  6.     private TestServiceImpl testService;   
  7.       
  8.     public void list() {   
  9.         //调用业务逻辑层方法  
  10.     }   
  11. }   
  12.     
  13.     
  14.    
package cn.javass.spring.chapter12.action;
//省略import
@Controller
public class TestAction {
    @Autowired
    private TestServiceImpl testService;
   
    public void list() {
        //调用业务逻辑层方法
    }
}
 
 
 

 

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

 

3、定义测试方法:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testWeb() {   
  3.     TestAction action = ctx.getBean("testAction", TestAction.class);   
  4.     Assert.assertNotNull(action);   
  5. }  
@Test
public void testWeb() {
    TestAction action = ctx.getBean("testAction", TestAction.class);
    Assert.assertNotNull(action);
}

    测试成功说明被@Controller注解的类将自动被Spring识别并注册到Spring容器中,且自动支持自动装配,并且被@Controller注解的类表示Web层实现。

 

大家是否注意到@Controller中并没有定义Bean的标识符,那么默认Bean的名字将是以小写开头的类名(不包括包名),即如“TestAction”类的Bean标识符为“testAction”。

 

 

 

六、自定义扩展:Spring内置了三种通用的扩展注解@Repository、@Service、@Controller ,大多数情况下没必要定义自己的扩展,在此我们演示下如何扩展@Component注解来满足某些特殊规约的需要;

 

在此我们可能需要一个缓存层用于定义缓存Bean,因此我们需要自定义一个@Cache的注解来表示缓存类。

 

 

1、扩展@Component:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.stereotype;   
  2. //省略import   
  3. @Target({ElementType.TYPE})   
  4. @Retention(RetentionPolicy.RUNTIME)   
  5. @Documented  
  6. @Component  
  7. public @interface Cache{   
  8.        String value() default "";   
  9. }   
  10.    
package cn.javass.spring.chapter12.stereotype;
//省略import
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Cache{
       String value() default "";
}
 

    扩展十分简单,只需要在扩展的注解上注解@Component即可,@Repository、@Service、@Controller也是通过该方式实现的,没什么特别之处

 

2、定义测试Bean类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.cache;   
  2. @Cache("cache")   
  3. public class TestCache {   
  4.     
  5. }  
package cn.javass.spring.chapter12.cache;
@Cache("cache")
public class TestCache {
 
}

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

 

 

3、定义测试方法:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testCache() {   
  3.     TestCache cache = ctx.getBean("cache", TestCache.class);   
  4.     Assert.assertNotNull(cache);   
  5. }  
@Test
public void testCache() {
    TestCache cache = ctx.getBean("cache", TestCache.class);
    Assert.assertNotNull(cache);
}

    测试成功说明自定义的@Cache注解也能很好的工作,而且实现了我们的目的,使用@Cache来表示被注解的类是Cache层Bean。

 

 

12.3.3  JSR-250中定义的@ManagedBean注解

@javax.annotation.ManagedBean需要在实现Java EE 6规范的应用服务器上使用,虽然Spring3实现了,但@javax.annotation.ManagedBean只有在Java EE 6环境中才有定义,因此测试前需要我们定义ManagedBean类。

 

 

1、定义javax.annotation.ManagedBean注解类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package javax.annotation;   
  2. import java.lang.annotation.ElementType;   
  3. import java.lang.annotation.Retention;   
  4. import java.lang.annotation.RetentionPolicy;   
  5. import java.lang.annotation.Target;   
  6. @Target(ElementType.TYPE)   
  7. @Retention(RetentionPolicy.RUNTIME)   
  8. public @interface ManagedBean {   
  9.      String value() default "";   
  10. }  
package javax.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ManagedBean {
     String value() default "";
}

其和@Component完全相同,唯一不同的就是名字和创建者(一个是Spring,一个是Java EE规范)。

 

 

2、定义测试Bean类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12;   
  2. import javax.annotation.Resource;   
  3. import org.springframework.context.ApplicationContext;   
  4. @javax.annotation.ManagedBean("managedBean")   
  5. public class TestManagedBean {   
  6.     @Resource  
  7.     private ApplicationContext ctx;   
  8.     public ApplicationContext getCtx() {   
  9.         return ctx;   
  10.     }   
  11. }  
package cn.javass.spring.chapter12;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
@javax.annotation.ManagedBean("managedBean")
public class TestManagedBean {
    @Resource
    private ApplicationContext ctx;
    public ApplicationContext getCtx() {
        return ctx;
    }
}

 

2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

 

 

3、定义测试方法:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testManagedBean() {   
  3.     TestManagedBean testManagedBean = ctx.getBean("managedBean", TestManagedBean.class);   
  4.     Assert.assertNotNull(testManagedBean.getCtx());   
  5. }  
@Test
public void testManagedBean() {
    TestManagedBean testManagedBean = ctx.getBean("managedBean", TestManagedBean.class);
    Assert.assertNotNull(testManagedBean.getCtx());
}

    测试成功说明被@ManagedBean注解类也能正常工作。

 

自定义扩展就不介绍了,大家可以参考@Component来完成如图12-2所示的自定义扩展部分。

 

 

12.3.4  JSR-330的@Named注解

@Named不仅可以用于依赖注入来指定注入的Bean的标识符,还可以用于定义Bean。即注解在类型上表示定义Bean,注解在非类型上(如字段)表示指定依赖注入的Bean标识符。

 

1、定义测试Bean类:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12;   
  2. //省略import   
  3. @Named("namedBean")   
  4. public class TestNamedBean {   
  5.     @Inject  
  6.     private ApplicationContext ctx;   
  7.     public ApplicationContext getCtx() {   
  8.         return ctx;   
  9.     }   
  10. }   
  11.    
package cn.javass.spring.chapter12;
//省略import
@Named("namedBean")
public class TestNamedBean {
    @Inject
    private ApplicationContext ctx;
    public ApplicationContext getCtx() {
        return ctx;
    }
}
 

 


2、Spring配置文件使用chapter12/ componentDefinitionWithAnnotation.xml即可且无需修改;

 

 

3、定义测试方法:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testNamedBean() {   
  3. TestNamedBean testNamedBean =   
  4.     ctx.getBean("namedBean", TestNamedBean.class);   
  5.     Assert.assertNotNull(testNamedBean.getCtx());   
  6. }  
@Test
public void testNamedBean() {
TestNamedBean testNamedBean =
    ctx.getBean("namedBean", TestNamedBean.class);
    Assert.assertNotNull(testNamedBean.getCtx());
}

 

测试成功说明被@Named注解类也能正常工作。

 

自定义扩展就不介绍了,大家可以参考@Component来完成如图12-3所示的自定义扩展部分。

 

 

12.3.5  细粒度控制Bean定义扫描

在XML配置中完全消除了Bean定义,而是只有一个<context:component-scan>标签来支持注解Bean定义扫描。

 

 

前边的示例完全采用默认扫描设置,如果我们有几个组件不想被扫描并自动注册、我们想更改默认的Bean标识符生成策略该如何做呢?接下来让我们看一下如何细粒度的控制Bean定义扫描,具体定义如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:component-scan   
  2.         base-package=""  
  3.         resource-pattern="**/*.class"  
  4.         name-generator="org.springframework.context.annotation.AnnotationBeanNameGenerator"  
  5.         use-default-filters="true"  
  6.         annotation-config="true">   
  7.                 <context:include-filter type="aspectj" expression=""/>   
  8.                 <context:exclude-filter type="regex" expression=""/>   
  9. </context:component-scan>     
<context:component-scan
        base-package=""
        resource-pattern="**/*.class"
        name-generator="org.springframework.context.annotation.AnnotationBeanNameGenerator"
        use-default-filters="true"
        annotation-config="true">
                <context:include-filter type="aspectj" expression=""/>
                <context:exclude-filter type="regex" expression=""/>
</context:component-scan>   
  • base-package:表示扫描注解类的开始位置,即将在指定的包中扫描,其他包中的注解类将不被扫描,默认将扫描所有类路径;
  • resource-pattern:表示扫描注解类的后缀匹配模式,即“base-package+resource-pattern”将组成匹配模式用于匹配类路径中的组件,默认后缀为“**/*.class”,即指定包下的所有以.class结尾的类文件;
  • name-generator:默认情况下的Bean标识符生成策略,默认是AnnotationBeanNameGenerator,其将生成以小写开头的类名(不包括包名);可以自定义自己的标识符生成策略;
  • use-default-filters:默认为true表示过滤@Component、@ManagedBean、@Named注解的类,如果改为false默认将不过滤这些默认的注解来定义Bean,即这些注解类不能被过滤到,即不能通过这些注解进行Bean定义;
  • annotation-config:表示是否自动支持注解实现Bean依赖注入,默认支持,如果设置为false,将关闭支持注解的依赖注入,需要通过<context:annotation-config/>开启。

默认情况下将自动过滤@Component、@ManagedBean、@Named注解的类并将其注册为Spring管理Bean,可以通过在<context:component-scan>标签中指定自定义过滤器将过滤到匹配条件的类注册为Spring管理Bean,具体定义方式如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:include-filter type="aspectj" expression=""/>   
  2. <context:exclude-filter type="regex" expression=""/>  
<context:include-filter type="aspectj" expression=""/>
<context:exclude-filter type="regex" expression=""/>
  • <context:include-filter>:表示过滤到的类将被注册为Spring管理Bean;
  • <context:exclude-filter>:表示过滤到的类将不被注册为Spring管理Bean,它比<context:include-filter>具有更高优先级;
  • type:表示过滤器类型,目前支持注解类型、类类型、正则表达式、aspectj表达式过滤器,当然也可以自定义自己的过滤器,实现org.springframework.core.type.filter.TypeFilter即可;
  • expression:表示过滤器表达式。

 

一般情况下没必要进行自定义过滤,如果需要请参考如下示例:

 

1、cn.javass.spring.chapter12.TestBean14自动注册为Spring管理Bean:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:include-filter type="assignable" expression="cn.javass.spring.chapter12.TestBean14"/>  
<context:include-filter type="assignable" expression="cn.javass.spring.chapter12.TestBean14"/>

 

2、把所有注解为org.aspectj.lang.annotation.Aspect自动注册为Spring管理Bean:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:include-filter type="annotation"  
  2. expression="org.aspectj.lang.annotation.Aspect"/>  
<context:include-filter type="annotation"
expression="org.aspectj.lang.annotation.Aspect"/>

 

3、将把匹配到正则表达式“cn\.javass\.spring\.chapter12\.TestBean2*”排除,不注册为Spring管理Bean:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:exclude-filter type="regex" expression="cn\.javass\.spring\.chapter12\.TestBean2*"/>  
<context:exclude-filter type="regex" expression="cn\.javass\.spring\.chapter12\.TestBean2*"/>

 

 

4、将把匹配到aspectj表达式“cn.javass.spring.chapter12.TestBean3*”排除,不注册为Spring管理Bean:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:exclude-filter type="aspectj" expression="cn.javass.spring.chapter12.TestBean3*"/>  
<context:exclude-filter type="aspectj" expression="cn.javass.spring.chapter12.TestBean3*"/>

 

具体使用就要看项目需要了,如果以上都不满足需要请考虑使用自定义过滤器。

 

 

12.3.6  提供更多的配置元数据

1、@Lazy:定义Bean将延迟初始化,使用方式如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Component("component")   
  2. @Lazy(true)   
  3. public class TestCompoment {   
  4. ……   
  5. }  
@Component("component")
@Lazy(true)
public class TestCompoment {
……
}

    使用@Lazy注解指定Bean需要延迟初始化。

 

 

2、@DependsOn:定义Bean初始化及销毁时的顺序,使用方式如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Component("component")   
  2. @DependsOn({"managedBean"})   
  3. public class TestCompoment {   
  4. ……   
  5. }  
@Component("component")
@DependsOn({"managedBean"})
public class TestCompoment {
……
}

 

 

3、@Scope:定义Bean作用域,默认单例,使用方式如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Component("component")   
  2. @Scope("singleton")   
  3. public class TestCompoment {   
  4. ……   
  5. }  
@Component("component")
@Scope("singleton")
public class TestCompoment {
……
}

 

 

 

4、@Qualifier:指定限定描述符,对应于基于XML配置中的<qualifier>标签,使用方式如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Component("component")   
  2. @Qualifier("component")   
  3. public class TestCompoment {   
  4. ……   
  5. }  
@Component("component")
@Qualifier("component")
public class TestCompoment {
……
}

    可以使用复杂的扩展,如@Mysql等等。

 

 

5、@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常,使用方式如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Component("component")   
  2. @Primary  
  3. public class TestCompoment {   
  4. ……   
  5. }  
@Component("component")
@Primary
public class TestCompoment {
……
}

 

 

 

 

 

 

12.4  基于Java类定义Bean配置元数据

12.4.1  概述

基于Java类定义Bean配置元数据,其实就是通过Java类定义Spring配置元数据,且直接消除XML配置文件。

 

基于Java类定义Bean配置元数据中的@Configuration注解的类等价于XML配置文件,@Bean注解的方法等价于XML配置文件中的Bean定义。

 

基于Java类定义Bean配置元数据需要通过AnnotationConfigApplicationContext加载配置类及初始化容器,类似于XML配置文件需要使用ClassPathXmlApplicationContext加载配置文件及初始化容器。

 

基于Java类定义Bean配置元数据需要CGLIB的支持,因此要保证类路径中包括CGLIB的jar包。

 

 

12.4.2  Hello World

首先让我们看一下基于Java类如何定义Bean配置元数据,具体步骤如下:

1、  通过@Configuration注解需要作为配置的类,表示该类将定义Bean配置元数据;

2、  通过@Bean注解相应的方法,该方法名默认就是Bean名,该方法返回值就是Bean对象;

3、  通过AnnotationConfigApplicationContext或子类加载基于Java类的配置。

 

 

 

接下来让我们先来学习一下如何通过Java类定义Bean配置元数据吧:

 

1、定义配置元数据的Java类如下所示:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.configuration;   
  2. import org.springframework.context.annotation.Bean;   
  3. import org.springframework.context.annotation.Configuration;   
  4. @Configuration    
  5. public class ApplicationContextConfig {   
  6.     @Bean  
  7.     public String message() {   
  8.         return "hello";   
  9.     }   
  10. }  
package cn.javass.spring.chapter12.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration 
public class ApplicationContextConfig {
    @Bean
    public String message() {
        return "hello";
    }
}

 

2、定义测试类,测试一下Java配置类是否工作:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.configuration;   
  2. //省略import   
  3. public class ConfigurationTest {   
  4.     @Test  
  5.     public void testHelloworld () {   
  6.         AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);   
  7.         Assert.assertEquals("hello", ctx.getBean("message"));   
  8.     }   
  9. }  
package cn.javass.spring.chapter12.configuration;
//省略import
public class ConfigurationTest {
    @Test
    public void testHelloworld () {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
        Assert.assertEquals("hello", ctx.getBean("message"));
    }
}

    测试没有报错说明测试通过了,那AnnotationConfigApplicationContext是如何工作的呢,接下来让我们分析一下:

  • 使用@Configuration注解配置类,该配置类定义了Bean配置元数据;
  • 使用@Bean注解配置类中的方法,该方法名就是Bean的名字,该方法返回值就是Bean对象。
  • 使用new AnnotationConfigApplicationContext(ApplicationContextConfig.class)创建应用上下文,构造器参数为使用@Configuration注解的配置类,读取配置类进行实例化相应的Bean。

 

知道如何使用了,接下来就详细介绍每个部分吧。

 

 

12.4.3  @Configuration

通过@Configuration注解的类将被作为配置类使用,表示在该类中将定义Bean配置元数据,且使用@Configuration注解的类本身也是一个Bean,使用方式如下所示:

 

java代码:
Java代码 复制代码  收藏代码
  1. import org.springframework.context.annotation.Configuration;   
  2. @Configuration("ctxConfig")   
  3. public class ApplicationContextConfig {   
  4.     //定义Bean配置元数据  
  5. }  
import org.springframework.context.annotation.Configuration;
@Configuration("ctxConfig")
public class ApplicationContextConfig {
    //定义Bean配置元数据
}

       因为使用@Configuration注解的类本身也是一个Bean,因为@Configuration被@Component注解了,因此@Configuration注解可以指定value属性值,如“ctxConfig”就是该Bean的名字,如使用“ctx.getBean("ctxConfig")”将返回该Bean。

 

使用@Configuration注解的类不能是final的,且应该有一个默认无参构造器。

 

12.4.4  @Bean

通过@Bean注解配置类中的相应方法,则该方法名默认就是Bean名,该方法返回值就是Bean对象,并定义了Spring IoC容器如何实例化、自动装配、初始化Bean逻辑,具体使用方法如下:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Bean(name={},   
  2.       autowire=Autowire.NO,   
  3.       initMethod="",   
  4.       destroyMethod="")  
@Bean(name={},
      autowire=Autowire.NO,
      initMethod="",
      destroyMethod="")
  • name:指定Bean的名字,可有多个,第一个作为Id,其他作为别名;
  • autowire:自动装配,默认no表示不自动装配该Bean,另外还有Autowire.BY_NAME表示根据名字自动装配,Autowire.BY_TYPE表示根据类型自动装配;
  • initMethod和destroyMethod:指定Bean的初始化和销毁方法。

示例如下所示(ApplicationContextConfig.java)

 

java代码:
Java代码 复制代码  收藏代码
  1. @Bean  
  2. public String message() {   
  3.     return new String("hello");   
  4. }  
@Bean
public String message() {
    return new String("hello");
}

 

如上使用方式等价于如下基于XML配置方式

 

java代码:
Java代码 复制代码  收藏代码
  1. <bean id="message" class="java.lang.String">   
  2.     <constructor-arg index="0" value="hello"/>   
  3. </bean>  
<bean id="message" class="java.lang.String">
    <constructor-arg index="0" value="hello"/>
</bean>

    使用@Bean注解的方法不能是private、final或static的。

 

 

12.4.5  提供更多的配置元数据

       详见【12.3.6  提供更多的配置元数据】中介绍的各种注解,这些注解同样适用于@Bean注解的方法。

 

 

12.4.6  依赖注入

  基于Java类配置方式的Bean依赖注入有如下两种方式:

  • 直接依赖注入,类似于基于XML配置方式中的显示依赖注入;
  • 使用注解实现Bean依赖注入:如@Autowired等等。

 

在本示例中我们将使用【第三章  DI】中的测试Bean。

 

1、 直接依赖注入:包括构造器注入和setter注入。

  • 构造器注入:通过在@Bean注解的实例化方法中使用有参构造器实例化相应的Bean即可,如下所示(ApplicationContextConfig.java):

 

java代码:
Java代码 复制代码  收藏代码
  1. @Bean  
  2. public HelloApi helloImpl3() {   
  3.     //通过构造器注入,分别是引用注入(message())和常量注入(1)  
  4.     return new HelloImpl3(message(), 1); //测试Bean详见【3.1.2  构造器注入】  
  5. }  
@Bean
public HelloApi helloImpl3() {
    //通过构造器注入,分别是引用注入(message())和常量注入(1)
    return new HelloImpl3(message(), 1); //测试Bean详见【3.1.2  构造器注入】
}

 

  • setter注入:通过在@Bean注解的实例化方法中使用无参构造器实例化后,通过相应的setter方法注入即可,如下所示(ApplicationContextConfig.java):

 

java代码:
Java代码 复制代码  收藏代码
  1. @Bean  
  2. public HelloApi helloImpl4() {   
  3.     HelloImpl4 helloImpl4 = new HelloImpl4();//测试Bean详见【3.1.3  setter注入】  
  4.     //通过setter注入注入引用  
  5.     helloImpl4.setMessage(message());   
  6.     //通过setter注入注入常量  
  7.     helloImpl4.setIndex(1);   
  8.     return helloImpl4;   
  9. }   
  10.    
@Bean
public HelloApi helloImpl4() {
    HelloImpl4 helloImpl4 = new HelloImpl4();//测试Bean详见【3.1.3  setter注入】
    //通过setter注入注入引用
    helloImpl4.setMessage(message());
    //通过setter注入注入常量
    helloImpl4.setIndex(1);
    return helloImpl4;
}
 

 

 

2、使用注解实现Bean依赖注入:详见【12.2  注解实Bean依赖注入】。

 

    具体测试方法如下(ConfigurationTest.java):

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testDependencyInject() {   
  3.     AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);   
  4.     ctx.getBean("helloImpl3", HelloApi.class).sayHello();   
  5.     ctx.getBean("helloImpl4", HelloApi.class).sayHello();   
  6. }  
@Test
public void testDependencyInject() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
    ctx.getBean("helloImpl3", HelloApi.class).sayHello();
    ctx.getBean("helloImpl4", HelloApi.class).sayHello();
}

 

12.4.7  方法注入

在基于XML配置方式中,Spring支持查找方法注入和替换方法注入,但在基于Java配置方式中只支持查找方法注入,一般用于在一个单例Bean中注入一个原型Bean的情况,具体详见【3.3.5  方法注入】,如下所示(ApplicationContextConfig.java):

 

java代码:
Java代码 复制代码  收藏代码
  1. @Bean  
  2. @Scope("singleton")   
  3. public HelloApi helloApi2() {   
  4.     HelloImpl5 helloImpl5 = new HelloImpl5() {   
  5.         @Override  
  6.         public Printer createPrototypePrinter() {   
  7.             //方法注入,注入原型Bean  
  8.             return prototypePrinter();   
  9.         }   
  10.         @Override  
  11.         public Printer createSingletonPrinter() {   
  12.             //方法注入,注入单例Bean  
  13.             return singletonPrinter();   
  14.         }   
  15.     };   
  16.     //依赖注入,注入单例Bean  
  17.     helloImpl5.setPrinter(singletonPrinter());   
  18.     return helloImpl5;   
  19. }  
@Bean
@Scope("singleton")
public HelloApi helloApi2() {
    HelloImpl5 helloImpl5 = new HelloImpl5() {
        @Override
        public Printer createPrototypePrinter() {
            //方法注入,注入原型Bean
            return prototypePrinter();
        }
        @Override
        public Printer createSingletonPrinter() {
            //方法注入,注入单例Bean
            return singletonPrinter();
        }
    };
    //依赖注入,注入单例Bean
    helloImpl5.setPrinter(singletonPrinter());
    return helloImpl5;
}

 

 

java代码:
Java代码 复制代码  收藏代码
  1. @Bean  
  2. @Scope(value="prototype")   
  3. public Printer prototypePrinter() {   
  4.     return new Printer();   
  5.  }   
  6. @Bean  
  7. @Scope(value="singleton")   
  8. public Printer singletonPrinter() {   
  9.     return new Printer();   
  10. }   
  11.    
@Bean
@Scope(value="prototype")
public Printer prototypePrinter() {
    return new Printer();
 }
@Bean
@Scope(value="singleton")
public Printer singletonPrinter() {
    return new Printer();
}
 

 

具体测试方法如下(ConfigurationTest.java):

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void testLookupMethodInject() {   
  3.     AnnotationConfigApplicationContext ctx =   
  4.         new AnnotationConfigApplicationContext(ApplicationContextConfig.class);   
  5.     System.out.println("=======prototype sayHello======");   
  6.     HelloApi helloApi2 = ctx.getBean("helloApi2", HelloApi.class);   
  7.     helloApi2.sayHello();   
  8.     helloApi2 = ctx.getBean("helloApi2", HelloApi.class);   
  9.     helloApi2.sayHello();   
  10. }  
@Test
public void testLookupMethodInject() {
    AnnotationConfigApplicationContext ctx =
        new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
    System.out.println("=======prototype sayHello======");
    HelloApi helloApi2 = ctx.getBean("helloApi2", HelloApi.class);
    helloApi2.sayHello();
    helloApi2 = ctx.getBean("helloApi2", HelloApi.class);
    helloApi2.sayHello();
}

    如上测试等价于【3.3.5  方法注入】中的查找方法注入。

 

 

12.4.8  @Import

  类似于基于XML配置中的<import/>,基于Java的配置方式提供了@Import来组合模块化的配置类,使用方式如下所示:

 

java代码:
Java代码 复制代码  收藏代码
  1. package cn.javass.spring.chapter12.configuration;   
  2. //省略import   
  3. @Configuration("ctxConfig2")   
  4. @Import({ApplicationContextConfig.class})   
  5. public class ApplicationContextConfig2 {   
  6.     @Bean(name = {"message2"})   
  7.     public String message() {   
  8.         return "hello";   
  9.     }   
  10. }  
package cn.javass.spring.chapter12.configuration;
//省略import
@Configuration("ctxConfig2")
@Import({ApplicationContextConfig.class})
public class ApplicationContextConfig2 {
    @Bean(name = {"message2"})
    public String message() {
        return "hello";
    }
}

 

具体测试方法如下(ConfigurationTest.java):

 

java代码:
Java代码 复制代码  收藏代码
  1. @Test  
  2. public void  importTest() {   
  3.     AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig2.class);   
  4.     Assert.assertEquals("hello", ctx.getBean("message"));   
  5. }  
@Test
public void  importTest() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig2.class);
    Assert.assertEquals("hello", ctx.getBean("message"));
}

   使用非常简单,在此就不多介绍了。

 

12.4.9  结合基于Java和基于XML方式的配置

基于Java方式的配置方式不是为了完全替代基于XML方式的配置,两者可以结合使用,因此可以有两种结合使用方式:

  • 在基于Java方式的配置类中引入基于XML方式的配置文件;
  • 在基于XML方式的配置文件中中引入基于Java方式的配置。

 

一、在基于Java方式的配置类中引入基于XML方式的配置文件:在@Configuration注解的配置类上通过@ImportResource注解引入基于XML方式的配置文件,示例如下所示:

1、定义基于XML方式的配置文件(chapter12/configuration/importResource.xml):

 

java代码:
Java代码 复制代码  收藏代码
  1. <bean id="message3" class="java.lang.String">   
  2.     <constructor-arg index="0" value="test"></constructor-arg>   
  3. </bean>  
<bean id="message3" class="java.lang.String">
    <constructor-arg index="0" value="test"></constructor-arg>
</bean>

 

2、修改基于Java方式的配置类ApplicationContextConfig,添加如下注解:

 

java代码:
Java代码 复制代码  收藏代码
  1. @Configuration("ctxConfig"//1、使用@Configuration注解配置类  
  2. @ImportResource("classpath:chapter12/configuration/importResource.xml")   
  3. public class ApplicationContextConfig {   
  4. ……   
  5. }  
@Configuration("ctxConfig") //1、使用@Configuration注解配置类
@ImportResource("classpath:chapter12/configuration/importResource.xml")
public class ApplicationContextConfig {
……
}

 

使用@ImportResource引入基于XML方式的配置文件,如果有多个请使用@ImportResource({"config1.xml", "config2.xml"})方式指定多个配置文件。

 

 

二、在基于XML方式的配置文件中中引入基于Java方式的配置:直接在XML配置文件中声明使用@Configuration注解的配置类即可,示例如下所示:

 

1、定义基于Java方式的使用@Configuration注解的配置类在此我们使用ApplicationContextConfig.java。

 

2、定义基于XML方式的配置文件(chapter12/configuration/xml-config.xml):

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:annotation-config/>   
  2. <bean id="ctxConfig" class="cn.javass.spring.chapter12.configuration.ApplicationContextConfig"/>  
<context:annotation-config/>
<bean id="ctxConfig" class="cn.javass.spring.chapter12.configuration.ApplicationContextConfig"/>
  • <context:annotation-config/>:用于开启对注解驱动支持,详见【12.2  注解实现Bean依赖注入】;
  • <bean id="ctxConfig" class="……"/>:直接将使用@Configuration注解的配置类在配置文件中进行Bean定义即可。

3、测试代码如下所示(ConfigurationTest.java)::

 

java代码:
Java代码 复制代码  收藏代码
  1. public void testXmlConfig() {   
  2.     String configLocations[] = {"chapter12/configuration/xml-config.xml"};   
  3.     ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations);   
  4.     Assert.assertEquals("hello", ctx.getBean("message"));   
  5. }  
public void testXmlConfig() {
    String configLocations[] = {"chapter12/configuration/xml-config.xml"};
    ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations);
    Assert.assertEquals("hello", ctx.getBean("message"));
}

 

测试成功,说明通过在基于XML方式的配置文件中能获取到基于Java方式的配置文件中定义的Bean,如“message”Bean。

 

 

12.4.10  基于Java方式的容器实例化

基于Java方式的容器由AnnotationConfigApplicationContext表示,其实例化方式主要有以下几种:

 

 

一、对于只有一个@Configuration注解的配置类,可以使用如下方式初始化容器:

 

java代码:
Java代码 复制代码  收藏代码
  1. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);  
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);

 

二、对于有多个@Configuration注解的配置类,可以使用如下方式初始化容器:

 

 

java代码:
Java代码 复制代码  收藏代码
  1. AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext(ApplicationContextConfig.class, ApplicationContextConfig2.class);  
AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext(ApplicationContextConfig.class, ApplicationContextConfig2.class);

 

或者

 

java代码:
Java代码 复制代码  收藏代码
  1. AnnotationConfigApplicationContext ctx2 = new AnnotationConfigApplicationContext();   
  2. ctx2.register(ApplicationContextConfig.class);   
  3. ctx2.register(ApplicationContextConfig2.class);  
AnnotationConfigApplicationContext ctx2 = new AnnotationConfigApplicationContext();
ctx2.register(ApplicationContextConfig.class);
ctx2.register(ApplicationContextConfig2.class);

 

 

三、对于【12.3  注解实现Bean定义】中通过扫描类路径中的特殊注解类来自动注册Bean定义,可以使用如下方式来实现:

 

java代码:
Java代码 复制代码  收藏代码
  1. public void testComponentScan() {   
  2.     AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();   
  3.     ctx.scan("cn.javass.chapter12.confiuration");   
  4.     ctx.refresh();   
  5.     Assert.assertEquals("hello", ctx.getBean("message"));   
  6. }  
public void testComponentScan() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.scan("cn.javass.chapter12.confiuration");
    ctx.refresh();
    Assert.assertEquals("hello", ctx.getBean("message"));
}

 

以上配置方式等价于基于XML方式中的如下配置:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context:component-scan base-package="cn.javass.chapter12.confiuration"/>  
<context:component-scan base-package="cn.javass.chapter12.confiuration"/>

 

 

四、在web环境中使用基于Java方式的配置,通过修改通用配置实现,详见【10.1.2 通用配置】

 

1、修改通用配置中的Web应用上下文实现,在此需要使用AnnotationConfigWebApplicationContext:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context-param>   
  2.     <param-name>contextClass</param-name>        
  3.     <param-value>   
  4.         org.springframework.web.context.support.AnnotationConfigWebApplicationContext   
  5.     </param-value>   
  6. </context-param>  
<context-param>
    <param-name>contextClass</param-name>     
    <param-value>
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
</context-param>

 

 

2、指定加载配置类,类似于指定加载文件位置,在基于Java方式中需要指定需要加载的配置类:

 

java代码:
Java代码 复制代码  收藏代码
  1. <context-param>   
  2.     <param-name>contextConfigLocation</param-name>   
  3.     <param-value>   
  4.         cn.javass.spring.chapter12.configuration.ApplicationContextConfig,   
  5.         cn.javass.spring.chapter12.configuration.ApplicationContextConfig2   
  6.     </param-value>   
  7. </context-param>  
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        cn.javass.spring.chapter12.configuration.ApplicationContextConfig,
        cn.javass.spring.chapter12.configuration.ApplicationContextConfig2
    </param-value>
</context-param>
  • contextConfigLocation:除了可以指定配置类,还可以指定“扫描的类路径”,其加载步骤如下:

      1、首先验证指定的配置是否是类,如果是则通过注册配置类来完成Bean定义加载,即如通过ctx.register(ApplicationContextConfig.class)加载定义;

      2、如果指定的配置不是类,则通过扫描类路径方式加载注解Bean定义,即将通过ctx.scan("cn.javass.chapter12.confiuration")加载Bean定义。

 

 

原创内容,转载请注明私塾在线【http://sishuok.com/forum/blogPost/list/0/2550.html

 

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值