天天看點

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啟動容器[email protected]注冊Bean

1.3、@Configuration啟動容器[email protected]注冊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啟動容器[email protected]注冊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啟動容器[email protected]注冊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)[email protected]配合使用》

5、使用外部變量

1、@PropertySource + Environment,通過@PropertySource注解将properties配置檔案中的值存儲到Spring的 Environment中,Environment接口提供方法去讀取配置檔案中的值,參數是properties檔案中定義的key值。

2、@PropertySource(PropertySourcesPlaceholderConfigurer)[email protected]

見《Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)[email protected]配合使用》

繼續閱讀