Spring Boot 配置文件解析

Spring Boot使用了一个全局的配置文件application.properties。

 

--- 自定义属性 ---

application.properties提供自定义属性的支持,这样我们就可以把一些常量配置在这里:

com.example.name=\u674E\u96F7
com.example.want=\u6765\u4E00\u676FSpring

然后,直接在要使用的地方通过注解@Value(value=”${config.name}”)就可以绑定到你想要的属性上面

@RestController
public class UserController {
	
    @Value("${com.example.name}")
    private  String name;
	
    @Value("${com.example.want}")
    private  String want;
    
    @RequestMapping("/want")
    public String doWant(){
        return name + "," + want;
    }
    
}

有时候属性太多,一个个绑定到属性字段上太累,官方提倡绑定一个对象的bean,这里我们建一个ConfigBean.java类,顶部需要使用注解@ConfigurationProperties(prefix = “com.example”)来指明使用哪个

@ConfigurationProperties(prefix = "com.example")
public class ConfigBean {
    private String name;
	
    private String want;

    // 省略get,set方法

}
这里配置完还需要在spring Boot入口类加上@EnableConfigurationProperties并指明要加载哪个bean,如果不写ConfigBean.class,可以在bean类那边添加。
@RestController
@SpringBootApplication
@EnableConfigurationProperties({ConfigBean.class})
public class MySpringBootApplication {
	@RequestMapping("/")
	public String index(){
		return "Hello Spring Boot";
	}
	
	public static void main(String[] args) {
		SpringApplication.run(MySpringBootApplication.class, args);
	}
}
最后在Controller中引入ConfigBean使用即可
@RestController
public class UserController {
    @Autowired
    private ConfigBean configBean;
    
    @RequestMapping("/want")
    public String doWant(){
        return configBean.getName() + "," + configBean.getWant();
    }
    
}
 

--- 参数间引用 ---

在application.properties中的各个参数之间也可以直接引用来使用,就像下面的设置:

com.example.hope=${com.example.name}\u7684\u613F\u671B${com.example.want}

--- 使用自定义配置文件 ---

有时候我们不希望把所有配置都放在application.properties里面,这时候我们可以自定义一个文件:test.properties,路径放在src/main/resources下面。

com.hx.company=\u6052\u5927
com.hx.address=\u4E0A\u6D77\u6D66\u4E1C

新建一个Bean

@Configuration
@ConfigurationProperties(prefix = "com.hx")
@PropertySource("classpath:test.properties")
public class ConfigTestBean {
    private String company;
	
    private String address;

    // 省略get,set方法

}
注意,如果你使用的是1.5以前的版本,那么可以通过locations指定properties文件的位置,这样:
@ConfigurationProperties(prefix = "config2",locations="classpath:test.properties")
 

--- 随机值配置 ---

配置文件中${random} 可以用来生成各种不同类型的随机值,从而简化了代码生成的麻烦,例如 生成 int 值、long 值或者 string 字符串。

com.example.secret=${random.value}
com.example.number=${random.int}
com.example.bignumber=${random.long}
com.example.uuid=${random.uuid}
com.example.number.less.than.ten=${random.int(10)}
com.example.number.in.range=${random.int[1024,65536]}

--- 外部配置 - 命令行参数配置 ---

Spring Boot是基于jar包运行的,打成jar包的程序可以直接通过下面命令运行:

java -jar xx.jar
可以以下命令修改tomcat端口号:
java -jar xx.jar --server.port=9090

可以看出,命令行中连续的两个减号--就是对application.properties中的属性值进行赋值的标识。
所以java -jar xx.jar --server.port=9090等价于在application.properties中添加属性server.port=9090


如果你怕命令行有风险,可以使用SpringApplication.setAddCommandLineProperties(false)禁用它。

实际上,Spring Boot应用程序有多种设置途径,Spring Boot能从多重属性源获得属性,包括如下几种:

  1. 根目录下的开发工具全局设置属性(当开发工具激活时为~/.spring-boot-devtools.properties)。
  2. 测试中的@TestPropertySource注解。
  3. 测试中的@SpringBootTest#properties注解特性。
  4. 命令行参数
  5. SPRING_APPLICATION_JSON中的属性(环境变量或系统属性中的内联JSON嵌入)。
  6. ServletConfig初始化参数。
  7. ServletContext初始化参数。
  8. java:comp/env里的JNDI属性
  9. JVM系统属性
  10. 操作系统环境变量
  11. 随机生成的带random.* 前缀的属性(在设置其他属性时,可以应用他们,比如${random.long})
  12. 应用程序以外的application.properties或者appliaction.yml文件
  13. 打包在应用程序内的application.properties或者appliaction.yml文件
  14. 通过@PropertySource标注的属性源
  15. 默认属性(通过SpringApplication.setDefaultProperties指定).

这里列表按组优先级排序,也就是说,任何在高优先级属性源里设置的属性都会覆盖低优先级的相同属性,列如我们上面提到的命令行属性就覆盖了application.properties的属性。

--- 配置文件的优先级 ---

application.properties和application.yml文件可以放在一下四个位置:

  • 外置,在相对于应用程序运行目录的/congfig子目录里。
  • 外置,在应用程序运行的目录里
  • 内置,在config包内
  • 内置,在Classpath根目录

同样,这个列表按照优先级排序,也就是说,src/main/resources/config下application.properties覆盖src/main/resources下application.properties中相同的属性。

此外,如果你在相同优先级位置同时有application.propertiesapplication.yml,那么application.yml里面的属性就会覆盖application.properties里的属性。

--- Profile - 多环境配置 ---

当应用程序需要部署到不同运行环境时,一些配置细节通常会有所不同。
如果按照以前的做法,就是每次发布的时候替换掉配置文件,这样太麻烦了,Spring Boot的Profile就给我们提供了解决方案,命令带上参数就搞定。

这里我们来模拟一下,只是简单的修改端口来测试
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境
  • application-prod.properties:生产环境

想要使用对应的环境,只需要在application.properties中使用spring.profiles.active属性来设置,值对应上面提到的{profile},这里就是指dev和prod。


当然你也可以用命令行启动的时候带上参数:

java -jar xxx.jar --spring.profiles.active=dev

除了可以用profile的配置文件来分区配置我们的环境变量,在代码里,我们还可以直接用@Profile注解来进行配置,例如数据库配置,这里我们先定义一个接口

public  interface DBConnector { 
    public  void  configure(); 
}

分别定义两个实现类来实现它

/**
  * 测试数据库
  */
@Component
@Profile("testdb")
public class TestDBConnector implements DBConnector {
    @Override
    public void configure() {
        System.out.println("testdb");
    }
}
/**
 * 生产数据库
 */
@Component
@Profile("devdb")
public class DevDBConnector implements DBConnector {
    @Override
    public void configure() {
        System.out.println("devdb");
    }
}

通过在配置文件激活具体使用哪个实现类

spring.profiles.active=testdb

然后就可以这么用了

@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired 
    DBConnector connector ;

    @RequestMapping(value = {"/",""})
    public String hellTask(){

        connector.configure();    
        return "hello task !! myage is " + myage;
    }
}

除了spring.profiles.active来激活一个或者多个profile之外,还可以用spring.profiles.include来叠加profile

spring.profiles.active: testdb  
spring.profiles.include: proddb,prodmq

http://tengj.top/2017/02/28/springboot2/#

猜你喜欢

转载自z724130632.iteye.com/blog/2372476