1.通過設定Environment的ActiveProfile來設置當前context所需要的環境配置,在開發中使用@Profile注解類或方法,達到不同情況下選擇實例化不同的Bean.
2.使用jvm的spring.profiles.acitve的參數來配置環境
3.web項目設置在Servlet的context pramater
servlet2.5一下的配置
<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>spring-profiles.active<param-name> <param-value>production</param-value> </init-param> </servlet>
servlet3.0以上的配置
public class WebInit implements WebApplicationInitializer{ @Override public void onStartup(ServletContext container) throws ServletException{ container.setInitParameter("spring.profiles.default", "dev"); } }
我沒有配置
實例:
DemoBean文件:
package ch2.profile; public class DemoBean { private String content; public DemoBean(String content) { this.content = content; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
profileConfig文件
package ch2.profile; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Configuration; //聲明本類是一個配置類 @Configuration public class ProfileConfig { //這個一個Bean對象 @Bean //profile為dev時實例化devDemoBean @Profile("dev") public DemoBean devDemoBean() { return new DemoBean("from development profile "); } //這是一個Bean對象 @Bean //profile為pro時實例化prDemoBean @Profile("prod") public DemoBean proDemoBean() { return new DemoBean("from production profile"); } }
Main文件:
package ch2.profile; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String args[]) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); //先將活動的profile注冊為prod context.getEnvironment().setActiveProfiles("prod"); //后注冊Bean配置類,不然會報Bean未定義的錯誤 context.register(ProfileConfig.class); //刷新容器 context.refresh(); //注冊Bean DemoBean demoBean = context.getBean(DemoBean.class); //打印 System.out.println(demoBean.getContent()); context.close(); } }
運行結果:
from production profile