一,类型安全的配置(基于properties)
- 使用
@Value注入每个配置会很麻烦(配置通常有许多个),SpringBoot还提供了基于类型安全的配置方式。 - 通过
@ConfigurationProperties将properties属性和一个 Bean 及其属性关联,从而实现类型安全的配置。
1,添加配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

2,创建类型安全的Bean
package com.zyf.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created by zyf on 2018/3/7.
*/
@Component
@ConfigurationProperties(prefix = "author")
//该注解可以加载properties中的配置
//通过prefix指定配置文件中的前缀
public class AuthorSettings {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
3,测试代码
package com.zyf;
import com.zyf.config.AuthorSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Springboot02Application {
@Autowired
private AuthorSettings authorSettings;
@RequestMapping("/")
public String index(){
return "author name is " + authorSettings.getName() + " author gender is " + authorSettings.getGender();
}
public static void main(String[] args) {
SpringApplication.run(Springboot02Application.class, args);
}
}
二,日志配置
默认情况下,SpringBoot使用 logback 作为日志框架
在 application.properties 中配置日志
#日志输出文件
logging.file=/Users/zyf/Desktop/SpringBootLog/sb2.log
#日志级别
logging.level.org.springframework.web=DEBUG
三,Profile配置(环境配置)
Profile 是 Spring 用来针对不同的环境对不同的配置提供支持的,全局 Profile 配置使用 application-{profile}.properties
- 开发环境:profile=dev
- 生产环境:profile=prod
示例
新建工程,分别配置开发环境和生产环境,开发环境端口号为8888,生产环境端口号为6666
1,创建两个file,名字为下图所示

2,内容


3,运行后查看日志信息


本文介绍SpringBoot中的类型安全配置方法,包括使用@ConfigurationProperties关联properties属性和Bean,简化配置注入过程;日志配置方法,通过application.properties文件配置logback;以及Profile配置,根据不同环境启用不同配置。
1万+

被折叠的 条评论
为什么被折叠?



