在软件开发的过程中,通常会经过开发环境,测试环境和生产环境;Spring中Profile的配置可以让我们不用担心这个问题.
配置profile bean
在Java配置中,可以使用@Profile注解指定某个bean属于哪一个profile.
package main.java.Demo1;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @author myvina@qq.com
* @date 18-4-16 上午8:53
*/
@Configuration
@Profile("dev")
public class CompactDiskConfig2 {
@Bean
public CompactDisc beatlesCD(){
return new BeatlesCD();
}
@Bean
public CDPlayer cdPlayer(){
return new CDPlayer(beatlesCD());
}
@Bean
public CDPlayer cdPlayer(CompactDisc compactDisc){
return new CDPlayer(compactDisc);
}
}
这里@Profile注解应用在了类级别上.它告诉Spring这个配置类中的bean只有在 dev profile激活时才会创建.如果 dev profile没有激活的话,那么带有@Bean注解的方法都会被忽略掉.
在Spring3.1中,只能在类级别使用@Profile注解,不过,从Spring3.2开始,也能在方法级别上使用@Profile注解,与@Bean注解一同使用,如下所示:
package main.java.Demo1;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @author myvina@qq.com
* @date 18-4-16 上午8:53
*/
@Configuration
public class CompactDiskConfig2 {
@Bean
@Profile("dev")
public CompactDisc beatlesCD(){
return new BeatlesCD();
}
@Bean
@Profile("prod")
public CDPlayer cdPlayer(){
return new CDPlayer(beatlesCD());
}
@Bean
@Profile("dev")
public CDPlayer cdPlayer(CompactDisc compactDisc){
return new CDPlayer(compactDisc);
}
}
只有当规定的profile激活时,响应的bean才会被创建,没有制定profile的bean始终都会被创建.
在XML中配置profile:
可以通过<beans>中的profile属性,在XML中配置profile bean.
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans profile="dev">
<bean id="devbeatlesCD" class="main.java.Demo1.BeatlesCD"/>
</beans>
<beans profile="qa">
<bean id="qabeatlesCD" class="main.java.Demo1.BeatlesCD"/>
</beans>
</beans>
可以在<beans>中嵌套定义<beans>元素,不用每个环境都创造一个profile XML文件
激活profile
Spring通过spring.profiles.active和spring.profiles.default来确定哪个profile处于激活状态.