025 使用@Profile完成环境条件注入

一 . 概述

在之前我们说过@Conditional注解可以帮助我们实现条件的Bean的注册,但有时候却不是很方便.

如我们在生产和测试环境是不同的,因此我们需要一个能够根据环境注入Bean的方式.

@Profile注解就能帮助我们实现这个功能.


 二 . 测试 

配置类:

@Configuration
public class ProfileConfig {
    
    @Bean("value")
    @Profile("test")
    public String test() {
        return "test";
    }
    
    @Bean
    @Profile("dev")
    public String dev() {
        return "dev";
    }
}

我们在test环境下会注入一个test的Bean,而在dev环境下会注入一个dev的Bean.

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {ProfileConfig.class})
public class ProfileTest {
    @Autowired
    @Qualifier("value")
    private String value;
    
    @Test
    public void test() {
        System.out.println(value);
    }
}

我们使用系统的环境变量,现在使用的环境是test环境.

spring会根据我们制定的系统运行参数注入不同的Bean.

 

posted @ 2018-05-27 00:24  最爱五仁月饼  阅读(142)  评论(0编辑  收藏  举报