Spring Boot实践——用外部配置填充Bean属性的几种方法

引用:https://blog.csdn.net/qq_17586821/article/details/79802320

  spring boot允许我们把配置信息外部化。由此,我们就可以在不同的环境中使用同一套程序代码。可以使用属性文件,yaml文件,环境变量,命令行参数来实现配置信息的外部化。可以使用@Value注解来将属性值直接注入到bean里边。也可以使用@ConfigurationProperties注解将属性值注入到结构化的对象里边。

@ConfigurationProperties

  Spring boot 应用中,当使用注解方式定义一个Bean时,同时可以利用@ConfigurationProperties导入外部属性填充到这个Bean的实例。本文通过例子介绍了几种用法可以达到这种效果 :

  • @ConfigurationProperties + @Component 注解到bean定义类上
  • @ConfigurationProperties + @Bean注解在配置类的bean定义方法上
  • @ConfigurationProperties注解到普通类然后通过@EnableConfigurationProperties定义为bean

  例子所采用配置文件
        先在例子项目增加配置文件 src/main/resources/application.properties ,其内容如下

section1.name=Tom
section2.name=Jerry
section3.name=Dog

        方式1 : @ConfigurationProperties + @Component 注解到bean定义类上类定义为Bean

        // 将类定义为一个bean的注解,比如 @Component,@Service,@Controller,@Repository
        // 或者 @Configuration
        @Component
        // 表示使用配置文件中前缀为 section1 的属性的值初始化该bean定义产生的的bean实例的同名属性
        // 在使用时这个定义产生的bean时,其属性 name 会是 Tom
        @ConfigurationProperties(prefix = "section1")
        public class Bean1 {
            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }
            
            private String name;
        }

        方式2 : @ConfigurationProperties + @Bean注解在配置类的bean定义方法上Bean来自一个普通类

        // 这是一个一般java类,POJO,没有任何注解
        public class Bean2 {
            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            private String name;
        }

  使用@Bean注解将一个配置类的方法定义为一个bean
        在项目的某个@Configuration配置类中通过@Bean注解在某个方法上将上面的POJO类定义为一个bean,并使用配置文件中相应的属性初始化该bean的属性。
        这里所说的@Configuration配置类可以是直接通过@Configuration注解的配置类,也可以是隐含使用了@Configuration注解的类,比如下面的例子中,@SpringBootApplication隐含了@Configuration。

        // 声明为Spring boot 应用,隐含了注解@Configuration
        @SpringBootApplication
        public class Application {
            // @Bean 注解在该方法上定义一个bean,这种基于方法的Bean定义不一定非要出现在
            // @SpringBootApplication 注解的类中,而是出现在任何@Configuration注解了
            // 的类中都可以
            @Bean
            // 使用配置文件中前缀为section2的属性的值初始化这里bean定义所产生的bean实例的同名属性,
            // 在使用时这个定义产生的bean时,其属性 name 会是 Jerry
            @ConfigurationProperties(prefix = "section2")
            public Bean2 bean2() {
                // 注意,这里的 Bean2 是上面所示的一个POJO类,没有任何注解
                return new Bean2();
            }

            public static void main(String[] args) throws Exception {
                SpringApplication.run(Application.class, args);
            }
        }

        方式3 : @ConfigurationProperties注解到普通类然后通过@EnableConfigurationProperties定义为bean

  注解一个普通类的属性将会来自外部属性文件

        // 该注解声明如果该类被定义为一个bean,则对应的bean实例的属性值将来自配置文件中前缀为
        // section3的同名属性。但是这个注解本身并不会导致该类被作为一个bean注册
        @ConfigurationProperties(prefix = "section3")
        public class Bean3 {
            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            private String name;
        }

        使用@EnableConfigurationProperties将上述类定义为一个bean

        @SpringBootApplication
        // 该注解会将类Bean3作为一个bean定义注册到bean容器,而类Bean3上的注解
        // @ConfigurationProperties(prefix = "section3")会导致目标bean
        // 实例的属性值使用配置文件中前缀为section3的同名属性值来填充,也就是目标
        // bean的属性name的值会是Dog
        @EnableConfigurationProperties({Bean3.class})
        public class Application {
            public static void main(String[] args) throws Exception {
                SpringApplication.run(Application.class, args);
            }
        }

 

注意重点:

  • 使用@ConfigurationProperties,在这种绑定中,getter 和 setter 方法是强制的,因为这里的绑定是通过标准的Java Bean属性绑定,但是也有例外。
  • 属性配置类的属性名和配置文件中配置信息是对应的(这里的对应并不是要求一模一样,只要能转换成功,就算对应,比如下划线语法、驼峰语法等都能接受)

 

@Value

  • @Value+ @Component 注解到bean定义类上
  • @Value+ @Bean注解在配置类的bean定义方法上

实现方式同上只是要写全对应的名

  配置文件

book.author=onlymate
book.name=Java is s magic

对应的bean

@Bean
//@Component
@PropertySource("classpath:files/el.properties")
public class CustomElConfig {
    //注入普通字符串
    @Value("I Love YOU!")
    private String normal;
    //注入操作系统属性
    @Value("#{systemProperties['os.name']}")
    private String osName;
    //注入表达式结果
    @Value("#{T(java.lang.Math).random()*100.0}")
    private double randomNumber;
    //注入其他的bean属性
    @Value("#{customElBean.another}")
    private String fromAnother;
    //注入文件资源
    @Value("classpath:files/test.txt")
    private Resource testFile;
    //注入网址资源
    @Value("http://www.baidu.com")
    private Resource testUrl;
    //注入配置文件
    @Value("${book.name}")
    private String bookNmame;
    @Value("${book.author}")
    private String bookAuthor;
    //注入环境
    @Autowired
    private Environment environment;
    
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
        return new PropertySourcesPlaceholderConfigurer();
    }
    
    public void outputResource(){
        try {
            System.out.println(normal);
            System.out.println(osName);
            System.out.println(randomNumber);
            System.out.println(fromAnother);
            System.out.println(IOUtils.toString(testFile.getInputStream(), Charset.defaultCharset()));
            System.out.println(IOUtils.toString(testUrl.getInputStream(), Charset.defaultCharset()));
            System.out.println(bookNmame);
            System.out.println(environment.getProperty("book.author"));
 
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e);
        }
    }

}

这里不需要写出set、get方法,属性名也任意,只要@Value("${book.author}")里面的key要对应配置文件中的key

 

posted @ 2018-12-12 19:56  路途寻码人  阅读(3103)  评论(0编辑  收藏  举报