开涛spring3(12.4) - 零配置 之 12.4 基于Java类定义Bean配置元数据

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类如下所示:

    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配置类是否工作:

    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,使用方式如下所示:

    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逻辑,具体使用方法如下:

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

示例如下所示(ApplicationContextConfig.java)

    @Bean
    public String message() {
        return new String("hello");
    }  

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

<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):
    @Bean
    public HelloApi helloImpl3() {
        //通过构造器注入,分别是引用注入(message())和常量注入(1)
        return new HelloImpl3(message(), 1); //测试Bean详见【3.1.2  构造器注入】
    }  

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

@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):

    @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):

    @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;
    }  
@Bean
@Scope(value="prototype")
public Printer prototypePrinter() {
    return new Printer();
 }
@Bean
@Scope(value="singleton")
public Printer singletonPrinter() {
    return new Printer();
}  

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

    @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来组合模块化的配置类,使用方式如下所示:

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

@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):

    <bean id="message3" class="java.lang.String">
        <constructor-arg index="0" value="test"></constructor-arg>
    </bean>  

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

    @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):

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

    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注解的配置类,可以使用如下方式初始化容器:

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);  

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

AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext(ApplicationContextConfig.class, ApplicationContextConfig2.class); 

或者

    AnnotationConfigApplicationContext ctx2 = new AnnotationConfigApplicationContext();
    ctx2.register(ApplicationContextConfig.class);
    ctx2.register(ApplicationContextConfig2.class);  

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

    public void testComponentScan() {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.scan("cn.javass.chapter12.confiuration");
        ctx.refresh();
        Assert.assertEquals("hello", ctx.getBean("message"));
    }  

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

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

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

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

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>  

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

    <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定义。

时间: 2024-08-02 04:11:45

开涛spring3(12.4) - 零配置 之 12.4 基于Java类定义Bean配置元数据的相关文章

【Spring】IOC之基于Java类的配置Bean

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 基于Java配置选项,可以编写大多数的Spring不用配置XML,但有几个基于Java的注释的帮助下解释.从Spring3.0开始支持使用java代码来代替XML来配置Spring,基于Java配置Spring依靠Spring的JavaConfig项目提供的很多优点.通过使用@Configuration, @Bean ,@Importand,@DependsOnannotations来实现J

Spring学习(16)--- 基于Java类的配置Bean 之 基于泛型的自动装配(spring4新增)

例子: 定义泛型Store package javabased; public interface Store<T> { } 两个实现类StringStore,IntegerStore package javabased; public class IntegerStore implements Store<Integer> { } package javabased; public class StringStore implements Store<String>

(五)使用注解开发,基于java类进行配置

1.使用注解代替bean 配置扫描哪些包下的注解 <!--指定注解扫描包--> <context:component-scan base-package="com.alan.pojo"/> 在指定包下编写类,增加注解 @Component("user") // 相当于配置文件中 <bean id="user" class="当前注解的类"/> public class User { publ

开涛spring3(12.2) - 零配置 之 12.2 注解实现Bean依赖注入

12.2  注解实现Bean依赖注入 12.2.1  概述 注解实现Bean配置主要用来进行如依赖注入.生命周期回调方法定义等,不能消除XML文件中的Bean元数据定义,且基于XML配置中的依赖注入的数据将覆盖基于注解配置中的依赖注入的数据. Spring3的基于注解实现Bean依赖注入支持如下三种注解: Spring自带依赖注入注解: Spring自带的一套依赖注入注解: JSR-250注解:Java平台的公共注解,是Java EE 5规范之一,在JDK6中默认包含这些注解,从Spring2.

开涛spring3(12.3) - 零配置 之 12.3 注解实现Bean定义

12.3  注解实现Bean定义 12.3.1  概述 前边介绍的Bean定义全是基于XML方式定义配置元数据,且在[12.2注解实现Bean依赖注入]一节中介绍了通过注解来减少配置数量,但并没有完全消除在XML配置文件中的Bean定义,因此有没有方式完全消除XML配置Bean定义呢? Spring提供通过扫描类路径中的特殊注解类来自动注册 Bean定义.同注解驱动事务一样需要开启自动扫描并注册Bean定义支持,使用方式如下(resources/chapter12/ componentDefin

开涛spring3(3.1) - DI的配置使用

3.1.1  依赖和依赖注入 传统应用程序设计中所说的依赖一般指“类之间的关系”,那先让我们复习一下类之间的关系: 泛化:表示类与类之间的继承关系.接口与接口之间的继承关系: 实现:表示类对接口的实现: 依赖:当类与类之间有使用关系时就属于依赖关系,不同于关联关系,依赖不具有“拥有关系”,而是一种“相识关系”,只在某个特定地方(比如某个方法体内)才有关系. 关联:表示类与类或类与接口之间的依赖关系,表现为“拥有关系”:具体到代码可以用实例变量来表示: 聚合:属于是关联的特殊情况,体现部分-整体关

开涛spring3(9.2) - Spring的事务 之 9.2 数据库事务概述

9.2.1  概述 Spring框架支持事务管理的核心是事务管理器抽象,对于不同的数据访问框架(如Hibernate)通过实现策略接口 PlatformTransactionManager,从而能支持各种数据访问框架的事务管理,PlatformTransactionManager 接口定义如下: public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition

开涛spring3(3.3) - DI 之 3.3 更多DI的知识

3.3.1  延迟初始化Bean 延迟初始化也叫做惰性初始化,指不提前初始化Bean,而是只有在真正使用时才创建及初始化Bean. 配置方式很简单只需在<bean>标签上指定 “lazy-init” 属性值为“true”即可延迟初始化Bean. Spring容器会在创建容器时提前初始化“singleton”作用域的Bean,“singleton”就是单例的意思即整个容器每个Bean只有一 个实例,后边会详细介绍.Spring容器预先初始化Bean通常能帮助我们提前发现配置错误,所以如果没有什么

开涛spring3(2.2) - IoC 容器基本原理及其helloword

2.2.1  IoC容器的概念 IoC容器就是具有依赖注入功能的容器,IoC容器负责实例化.定位.配置应用程序中的对象及建立这些对象间的依赖.应用程序无需直接在代码中new相关的对象,应用程序由IoC容器进行组装.在Spring中BeanFactory是IoC容器的实际代表者. Spring IoC容器如何知道哪些是它管理的对象呢?这就需要配置文件,Spring IoC容器通过读取配置文件中的配置元数据,通过元数据对应用中的各个对象进行实例化及装配.一般使用基于xml配置文件进行配置元数据,而且