spring4.0之:@Configuration的使用

 

从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

注意:@Configuration注解的配置类有如下要求:

  1. @Configuration不可以是final类型;
  2. @Configuration不可以是匿名类;
  3. 嵌套的configuration必须是静态类。

一、用@Configuration加载spring
1.1、@Configuration配置spring并启动spring容器
1.2、@Configuration启动容器+@Bean注册Bean
1.3、@Configuration启动容器+@Component注册Bean
1.4、使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法
1.5、配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)

二、组合多个配置类
2.1、在@configuration中引入spring的xml配置文件
2.2、在@configuration中引入其它注解配置
2.3、@configuration嵌套(嵌套的Configuration必须是静态类)
三、@EnableXXX注解
四、@Profile逻辑组配置
五、使用外部变量

一、@Configuation加载Spring方法

1.1、@Configuration配置spring并启动spring容器

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class TestConfiguration {

	public TestConfiguration(){
		System.out.println("容器初始化。。。");
	}	
}

相当于:

<?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" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">


</beans>

1.2、@Configuration启动容器+@Bean注册Bean,@Bean下管理bean的生命周期

@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的<bean>,作用为:注册bean对象

bean类:

public class UserVO {
	private String userName;
	
	private String password;
	
	private String url;

    public void sayHello() {
        System.out.println("UserVO sayHello...");
    }

    public String toString() {
        return "username:" + this.userName + ",url:" + this.url + ",password:" + this.password;
    }

    public void start() {
        System.out.println("UserVO 初始化。。。");
    }

    public void cleanUp() {
        System.out.println("UserVO 销毁。。。");
    }

}

配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class TestConfiguration {

	public TestConfiguration(){
		System.out.println("容器初始化。。。");
	}
	
	@Bean
	@Scope("prototype")
	public UserVO userBean(){
		return new UserVO();
	}
	
}

主方法测试类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {
    public static void main(String[] args) {

        // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

        // 如果加载spring-context.xml文件:
        // ApplicationContext context = new
        // ClassPathXmlApplicationContext("spring-context.xml");
        
         //获取bean
        UserVOtb = (UserVO) context.getBean("UserVO");
        tb.sayHello();
    }
}

注入方法测试:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
public class HelloController {
	@Autowired
	private UserVO userVO;

	@GetMapping("usersay")
	public String userSayHello(){
		userVO.sayHello();
		return userVO.toString();
	}

}

注: 
(1)、@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; 
(2)、@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; 
(3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。

@Bean下管理bean的生命周期

可以使用基于 Java 的配置来管理 bean 的生命周期。@Bean 支持两种属性,即 initMethod 和destroyMethod,这些属性可用于定义生命周期方法。在实例化 bean 或即将销毁它时,容器便可调用生命周期方法。生命周期方法也称为回调方法,因为它将由容器调用。使用 @Bean 注释注册的 bean 也支持 JSR-250 规定的标准 @PostConstruct 和 @PreDestroy 注释。如果您正在使用 XML 方法来定义 bean,那么就应该使用 bean 元素来定义生命周期回调方法。以下代码显示了在 XML 配置中通常使用 bean 元素定义回调的方法。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class TestConfiguration {
	public TestConfiguration(){
		System.out.println("容器初始化。。。");
	}
	
	@Bean(name="userBean",initMethod="start",destroyMethod="cleanUp")
	@Scope("prototype")
	public UserVO userBean(){
		return new UserVO();
	}
	
}

启动显示:

容器初始化。。。
UserVO 初始化。。。

表明initMethod生效

1.3、@Configuration启动容器+@Component注册Bean

@Component
public class UserVO {
	private String userName;
	
	private String password;
	
	private String url;

    public void sayHello() {
        System.out.println("UserVO sayHello...");
    }

    public String toString() {
        return "username:" + this.userName + ",url:" + this.url + ",password:" + this.password;
    }

    public void start() {
        System.out.println("UserVO 初始化。。。");
    }

    public void cleanUp() {
        System.out.println("UserVO 销毁。。。");
    }

}

配置:

@Configuration
public class TestConfiguration {

	public TestConfiguration(){
		System.out.println("容器初始化。。。");
	}
	
//	@Bean(name="userBean",initMethod="start",destroyMethod="cleanUp")
//	@Scope("prototype")
//	public UserVO userBean(){
//		return new UserVO();
//	}
	
}

也是能正常调用

1.4、使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法

1.4.1、 配置类的注册方式是将其传递给 AnnotationConfigApplicationContext 构造函数

public static void main(String[] args) {

        // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

        //获取bean
        UserVO tb = (TestBean) context.getBean("UserVO");
        tb.sayHello();
    }

1.4.2、 AnnotationConfigApplicationContext 的register 方法传入配置类来注册配置类

public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext();
  ctx.register(AppContext.class)
}

 

1.6、@Configuation总结

 @Configuation等价于<Beans></Beans>

 @Bean等价于<Bean></Bean>

 @ComponentScan等价于<context:component-scan base-package="com.dxz.demo"/>

二、组合多个配置类

2.1、在@configuration中引入spring的xml配置文件

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:applicationContext-configuration.xml")
public class WebConfig {
}

 2.2、在@configuration中引入其它注解配置

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

import com.dxz.demo.configuration.TestConfiguration;

@Configuration
@ImportResource("classpath:applicationContext-configuration.xml")
@Import(TestConfiguration.class)
public class WebConfig {
}

2.3、@configuration嵌套(嵌套的Configuration必须是静态类)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.dxz.demo.configuration3")
public class TestConfiguration {
    public TestConfiguration() {
        System.out.println("TestConfiguration容器启动初始化。。。");
    }
    
    @Configuration
    static class DatabaseConfig {
        @Bean
        DataSource dataSource() {
            return new DataSource();
        }
    }
}

3、@EnableXXX注解

配合@Configuration使用,包括 @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, @EnableWebMvc。

@EnableAspectJAutoProxy---《spring AOP 之:@Aspect注解

@EnableScheduling--《Spring 3.1新特性之二:@Enable*注解的源码,spring源码分析之定时任务Scheduled注解

 

4、@Profile逻辑组配置

见《Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value配合使用

5、使用外部变量

1、@PropertySource + Environment,通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
2、@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value

见《Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value配合使用

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值