[十六]SpringBoot 之 读取环境变量和绑定属性对象

时间:2017-03-06 13:54:26   收藏:0   阅读:9374

 

1.读取环境变量

凡是被spring管理的类,实现接口EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,获取到系统环境变量和application配置文件中的变量。

主要是@Configuration,实现接口:EnvironmentAware就能获取到系统环境信息

package me.shijunjie.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class MyEnvironmentAware implements EnvironmentAware {

    @Value("${spring.datasource.url}")
    private String url;

    @Override
    public void setEnvironment(Environment env) {
        //打印注入的属性信息.
        System.out.println(url);
        //通过 environment 获取到系统属性.
        System.out.println(env.getProperty("JAVA_HOME"));
         //通过 environment 同样能获取到application.properties配置的属性.
        System.out.println(env.getProperty("spring.datasource.url"));
        //获取到前缀是"spring.datasource." 的属性列表值.
        RelaxedPropertyResolver relaxedPropertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
        System.out.println("spring.datasource.url="+relaxedPropertyResolver.getProperty("url"));
        System.out.println("spring.datasource.driverClassName="+relaxedPropertyResolver.getProperty("driverClassName"));
    }

}

启动应用

技术分享

@Controller@Service 等被Spring管理的类都支持,注意重写的方法setEnvironment 是在系统启动的时候被执行。 
或者如下Controller:

package me.shijunjie.controller;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test2")
public class TestController implements EnvironmentAware {
    
    /*@Resource(name="TestAutoConfiguration2")
    private TestAutoConfiguration testAutoConfiguration;*/

    @Override
    public void setEnvironment(Environment env) {
        String s= env.getProperty("JAVA_HOME");
        System.out.println("JAVA_HOME2"+s);
    }
    
    
    @RequestMapping("/hello")
    public String test() {
        
        /*System.out.println(testAutoConfiguration.getDataSourceProperties().getName());
        System.out.println(testAutoConfiguration.getDataSourceProperties().getPassword());
        System.out.println(testAutoConfiguration.getDataSourceProperties().getUrl());*/
        return "hello";
    }

}

启动应用

技术分享

2.绑定属性对象

我们还可以通过@ConfigurationProperties 读取application属性配置文件中的属性。

package me.shijunjie.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import me.shijunjie.properties.DataSourceProperties;

@Configuration
@ConditionalOnClass(DataSourceProperties.class)
@EnableConfigurationProperties(DataSourceProperties.class)
public class TestAutoConfiguration {
    @Autowired
    private DataSourceProperties dataSourceProperties;
    
    @Bean(name="TestAutoConfiguration2")
    public TestAutoConfiguration setTestAutoConfiguration() {
        return this;
    }

    public DataSourceProperties getDataSourceProperties() {
        return dataSourceProperties;
    }

    public void setDataSourceProperties(DataSourceProperties dataSourceProperties) {
        this.dataSourceProperties = dataSourceProperties;
    }
    
    
}
package me.shijunjie.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties {
    private String url;
    private String name = "testName";
    private String password;
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
}

 @ConditionOnClass表明该@Configuration仅仅在一定条件下才会被加载,这里的条件是DataSourceProperties.class位于类路径上

@EnableConfigurationProperties将Spring Boot的配置文件(application.properties)中的spring.datasource.*属性映射为DataSourceProperties并注入到TestAutoConfiguration中。

@ConditionalOnMissingBean说明Spring Boot仅仅在当前上下文中不存在指定对象时,才会实例化一个Bean。这个逻辑也体现了Spring Boot的另外一个特性——自定义的Bean优先于框架的默认配置,我们如果显式的在业务代码中定义了一个对象,那么Spring Boot就不再创建。

测试

package me.shijunjie.controller;

import javax.annotation.Resource;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import me.shijunjie.config.TestAutoConfiguration;

@RestController
@RequestMapping("/test2")
public class TestController implements EnvironmentAware {
    
    @Resource(name="TestAutoConfiguration2")
    private TestAutoConfiguration testAutoConfiguration;

    @Override
    public void setEnvironment(Environment env) {
        String s= env.getProperty("JAVA_HOME");
        System.out.println("JAVA_HOME2"+s);
    }
    
    
    @RequestMapping("/hello")
    public String test() {
        
        System.out.println(testAutoConfiguration.getDataSourceProperties().getName());
        System.out.println(testAutoConfiguration.getDataSourceProperties().getPassword());
        System.out.println(testAutoConfiguration.getDataSourceProperties().getUrl());
        return "hello";
    }

}

打开浏览器,输入地址http://localhost:8080/test2/hello

技术分享

技术分享

这里告诉我们DataSourceProperties就是以spring.datasource作为前缀的属性,然后通过名字直接映射为对象的属性,同时还包含了一些默认值。如果不配置,那么spring.datasource.username就是jdbc:mysql://123.206.228.200:3306/test

 网上资料上写绑定属性对象需要添加依赖(我没有加)

<!--spring-boot-configuration:springboot 配置处理器; -->

              <dependency>

                     <groupId>org.springframework.boot</groupId>

                     <artifactId>spring-boot-configuration-processor</artifactId>

                     <optional>true</optional>

              </dependency>

这边是我的application.properties文件

########################################################
###datasource
########################################################

spring.datasource.url = jdbc:mysql://123.206.228.200:3306/test

spring.datasource.username = shijunjie

spring.datasource.password = *****

spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.max-active=20

spring.datasource.max-idle=8

spring.datasource.max-maxWait=100

spring.datasource.min-idle=8

spring.datasource.initial-size=10

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!