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

原文地址:https://www.cnblogs.com/achengmu/p/8118946.html