配置profile bean
Spring为环境相关的bean所提供的解决方案其实和构建时候的方案没有太大区别,Spring会根据环境决定该创建那个bean和
不创建那个bean。
Spring的bean profile的功能。要使用profile,首先将所有不同的bean定义到一个或者多个profile之中,在将应用部署到每个环境中,要确保对应的profile处于激活(active)的状态
* Java配置中,使用@Profile注解指定某个bean属于那个profile
首先创建一个bean,用在开发环境和生产环境
@Configuration
@Profile("dev")
public class DevConfiguration {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld("dev environment .....");
}
}
@Configuration
@Profile("prod")
public class ProductConfiguration {
public HelloWorld helloWorld(){
return new HelloWorld("product environment .... ");
}
}
从Spring3.2开始,profile注解可以用在方法上,上面改为
@Configuration
public class HellloConfiguration {
@Bean
@Profile("dev")
public HelloWorld devhelloWorld(){
return new HelloWorld("dev environment .....");
}
@Bean
@Profile("prod")
public HelloWorld prodhelloWorld(){
return new HelloWorld("product environment .....");
}
}
只有规定的profile被激活,对应的bean才会被创建,没有指定profile的Bean始终都会创建
* XML中配置profile
* Beans标签使用profile属性表示当前的bean的profile
<?xml version="1.0" encoding="UTF-8"?>
<beans profile="dev" 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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
">
<bean id="helloWorld" class="com.erong.service.HelloWorld">
<property name="message" value="dev bean ....."></property>
</bean>
</beans>
需要注意的是xsi:schemaLoc