spring boot: 一般注入說明(四) Profile配置,Environment環境配置 @Profile注解


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM