• 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.

  • 相关阅读:
    windows-DLL注入
    HDU 2148 Score
    HDU 2133 What day is it
    HDU 2112 HDU Today
    HDU 2187 悼念512汶川大地震遇难同胞——老人是真饿了
    HDU 2124 Repair the Wall
    HDU 2117 Just a Numble
    HDU 2114 Calculate S(n)
    HDU 2115 I Love This Game
    HDU 2104 hide handkerchief
  • 原文地址:https://www.cnblogs.com/trekxu/p/9094885.html
Copyright © 2020-2023  润新知