10、多环境切换-@Profile、@Environment.setActiveProfiles

Profile为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如,数据库的配置)。

bean:

public class ProfileBean {
	private String content;
    
    public void setContent(String content) {
		this.content = content;
	}
	public String getContent() {
		return content;
	};
	
	public ProfileBean(String content) {
		this.content = content;
	}
}

配置类:

@Configuration
@ComponentScan("com.demo02.profile")
public class ProfileConfig {
	@Bean
	@Profile("dev")
	public ProfileBean depDemo() {
		return new ProfileBean("development  开发环境");
	}
	
	@Bean
	@Profile("prod")
	public ProfileBean prodDemo() {
		return new ProfileBean("production 生产环境");
	}
}

@Profile("dev"):表示当前为dev时,才会执行该方法。
@Profile("prod"):表示当前为prod时,才会执行该方法。

测试运行:

public class App {
	public static void main(String[] args) {
	    //1、因为配置类,需重新指定模式(开发或是生产等),所以在新建annotation时,不用加载配置类。
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		//2、使用Environment来指定当前运行的模式,指定的值必须和@Profile注解中自定义的值匹配。否则都不执行。
		context.getEnvironment().setActiveProfiles("prod");
		//3、指定模式后,再注册Bean
		context.register(ProfileConfig.class);
		//4、刷新容器,注册生效。
		context.refresh();
		
		ProfileBean bean = context.getBean(ProfileBean.class);
		System.out.println(bean.getContent());
		
		context.close();
	}
}

注意:
1、需要调整配置类,在创建Annotation时,就不用指定配置类。
2、根据Environment中的setActiveProfiles("指定模式"),来指定当前运行的模式,指定模式需要与配置类中设置的值对应。
3、指定模式后,需要注册配置类
4、最后刷新容器,注册的配置类才会生效。
5、可在类上加@ActiveProfiles("dev")注解替代Environment.setActiveProfiles("dev") 。
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值