博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot之读取配置文件
阅读量:7109 次
发布时间:2019-06-28

本文共 6209 字,大约阅读时间需要 20 分钟。

引入依赖

org.springframework.boot
spring-boot-starter

application.properties 默认配置文件

local.ip=192.168.1.1local.port=8080local.test=this is test multi file
  • 第一种方式 注入Environment,同时也可以指定默认值
package vip.fkandy.demo01;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.env.Environment;import org.springframework.stereotype.Component;import lombok.extern.slf4j.Slf4j;@Component@Slf4jpublic class UserConfig {    @Autowired    private Environment env; //不需要getter setter方法    public void show() {        log.info("local.ip: " + env.getProperty("local.ip"));    }}
  • 第二种方式 使用@Value("${local.ip}")方式
package vip.fkandy.demo01;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import lombok.extern.slf4j.Slf4j;@Slf4j@Componentpublic class JdbcConfig {    @Value("${local.ip}")    private String localIp;  //不需要getter setter方法    public void show() {        log.info("Jdbc ip: " + localIp);    }}
  • 使用@Value("${local.ip}")方式,并指定默认值
package vip.fkandy.demo01;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import lombok.extern.slf4j.Slf4j;@Component@Slf4jpublic class DogConfig {    @Value("${local.ip:8080}")    private String localPort;//不需要getter setter方法    public void show() {        log.info("dog ip :" + localPort);    }}

配置文价默认名字为application.properties,默认位置在classpath根目录,或者classpath:/config,file:/,file:config目录默认配置文件名字可以使用--spring.config.name来指定,只需要指定文件名字,文件扩展名可以省略,默认的配置文件路径可以使用--spring.config.location=classpath:conf/app.properties指定具体文件位置,配置文件名需要指定全路径,包括目录和文件名字,还可以指定多个,用逗号隔开

  • 【自定义配置文件】定义一个配置类@Configuration和@PropertySource(value = {classpath:application.properties" }),之后再其他容器bean中使用@Value取值
@Configuration@PropertySource(value = {"classpath:a.properties" })    //可以引用自定义名字的配置文件public class CatConfig {}

也可以指定多个配置文件

@PropertySources({@PropertySource("classpath:a.properties" ),@PropertySource("classpath:b.properties" )})
  • 第三种方式 根据前缀指定
package vip.fkandy.demo01;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import lombok.Data;import lombok.extern.slf4j.Slf4j;@Component //需要加入到Spring容器@ConfigurationProperties(prefix = "local")@Slf4j@Datapublic class LastConfig {    private String ip;    private String port;    public void show() {        log.info("ip:{},port:{}",ip,port);    }}

测试类

package vip.fkandy.demo01;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;import lombok.extern.slf4j.Slf4j;@SpringBootApplication@Slf4jpublic class Application {    public static void main(String[] args) {        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);        log.info(context.getEnvironment().getProperty("local.ip"));        log.info("-------测试 @PropertySource 指定配置文件---------------------------");        log.info(context.getEnvironment().getProperty("local.address"));        log.info("-------测试默认配置文件和@PropertySource 指定配置文件同时能生效-----");        log.info(context.getEnvironment().getProperty("local.test"));        log.info("-------@Autowired Environment method---------------------------");        context.getBean(UserConfig.class).show();        log.info("-------@Value(\"${local.ip}\") method --------------------");        context.getBean(DogConfig.class).show();        log.info("-------@Value(\"${local.ip:8080}\") default value method ------");        context.getBean(JdbcConfig.class).show();        log.info("-------@ConfigurationProperties method ------------------------");        context.getBean(LastConfig.class).show();    }}

支持在配置中使用${}引用之前写好的配置

  • 注入集合
ds.hosts[0]=192.168.0.1ds.hosts[1]=192.168.0.2
@Component@ConfigurationProperties("ds")public class TomcatProperties{    private List
hosts = new ArrayList
(); public List
getHosts(){ return hosts; } public void setHosts(List
hosts){ this.hosts = hosts; }}
  • 动态引用配置文件-配置文件集中化管理-可以通过HttpClient读取集中化管理的配置文件
package com.example.demo;import java.io.FileInputStream;import java.io.InputStream;import java.util.Properties;import org.springframework.boot.SpringApplication;import org.springframework.boot.env.EnvironmentPostProcessor;import org.springframework.core.env.ConfigurableEnvironment;import org.springframework.core.env.PropertiesPropertySource;/** * 动态读取d:/tmp/springboot.properties */public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {    @Override    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {        try {            InputStream input = new FileInputStream("d:/tmp/springboot.properties");            Properties source = new Properties();            source.load(input);            PropertiesPropertySource propertySource = new PropertiesPropertySource("my", source);            environment.getPropertySources().addLast(propertySource);        } catch (Exception e) {            e.printStackTrace();        }    }}

srcmainresourcesMETA-INFspring.factories

org.springframework.boot.env.EnvironmentPostProcessor=com.example.demo.MyEnvironmentPostProcessor
package com.example.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;@SpringBootApplicationpublic class Springboot15DynamicConfigApplication {    public static void main(String[] args) {        ConfigurableApplicationContext context = SpringApplication.run(Springboot15DynamicConfigApplication.class, args);        System.out.println(context.getEnvironment().getProperty("local.ip"));    }}

通过运行环境动态注入Bean--->基于代码层面,也可以直接动态指定peroperties文件

public class MyConfig{        @Bean    @Profile("test")//这个注解也可以放在类上    public Runnable createRunnable(){        return ()->{};    }        @Bean    @Profile("dev")    public Runnable createRunnable(){        return ()->{};    }}

--spring.profiles.active=dev 表示激活dev配置

转载地址:http://xovhl.baihongyu.com/

你可能感兴趣的文章
Centos6.5搭建Wiki
查看>>
linux 清空文件内容的方法
查看>>
2018“硅谷技划”随笔(三):人工智能火热背后的真正温度
查看>>
综合技术 --ORM
查看>>
我的友情链接
查看>>
OSPF详解-3 邻接、度量值
查看>>
剖析布隆过滤器
查看>>
使用Eclipse的Egit插件在Git@OSC上进行项目管理
查看>>
MA5620与U1960链接配置
查看>>
Netty学习:搭建一个简单的Netty服务
查看>>
[C++]STL萃取学习
查看>>
httpClient学习
查看>>
使用vue实现数组对象排序
查看>>
Binder的工作机制浅析
查看>>
linux
查看>>
织梦dedecms安全设置
查看>>
【刘文彬】EOS多节点组网:商业场景分析以及节点启动时序
查看>>
函数指针和指针函数的区别
查看>>
贪吃蛇小游戏
查看>>
搭建Mycat实现读写分离
查看>>