spring 相关

spring注解--Profile

2019-01-02  本文已影响0人  aix91

1. 作用

根据当前环境,动态的激活切换注入的bean;使用该功能,可以实现测试环境,生产环境的切换。

2. 用法

3. 实例

  1. 给要注入的bean设置profile属性
@Configuration
public class MainConfig {
    @Profile("test")
    @Bean(name = "test")
    public TestBean testBean() {
        return new TestBean();
    }
    @Profile("dev")
    @Bean(name = "dev")
    public DevBean devBean() {
        return new DevBean();
    }
    @Profile("prod")
    @Bean(name = "prod")
    public ProdBean prodBean() {
        return new ProdBean();
    }
}
  1. 设置context环境属性
public class ProfileDemo {
    public static void main(String[] args) {
//        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        //构建无参构造器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        //设置环境变量
        context.getEnvironment().setActiveProfiles("test");
        //注册configuration 类
        context.register(MainConfig.class);
        context.refresh();
        Arrays.stream(context.getBeanDefinitionNames()).forEach(p ->
                System.out.println(p)
        );
    }
  1. 输出,查看注入到容器中的bean
mainConfig
...
test --> 注入的testBean

4. Notes

没有设置profile属性的bean,在任何环境下都可以注入。

上一篇 下一篇

猜你喜欢

热点阅读