背景
@ConfigurationProperties
注解可以将配置文件自动封装成javabean,方便调用,SpringBoot的自动配置,使用了此特性。在Spring Bean中读取配置文件属性,可以使用@Value
注解,也可以使用@ConfigurationProperties
注入封装好的配置对象,后者在存在大量属性时方便很多。
自定义配置类
springboot项目
springboot项目中可直接定义使用
配置类:
package top.freej.demo.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "demo.config")
public class ConfigurationDemo {
private String key1;
private String key2;
private Complex complex = new Complex();
@Data
public class Complex {
private String key1;
private String key2;
}
}
配置文件
demo:
config:
key1: "key1"
key2: "key2"
complex:
key1: "complexKey1"
key2: "complexKey2"
测试
package top.freej.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import top.freej.demo.config.ConfigurationDemo;
import javax.annotation.Resource;
@SpringBootTest
class DemoApplicationTests {
@Resource
private ConfigurationDemo configurationDemo;
@Test
public void testConfig() {
Assertions.assertEquals("key1", configurationDemo.getKey1());
Assertions.assertEquals("key2", configurationDemo.getKey2());
Assertions.assertEquals("complexKey1", configurationDemo.getComplex().getKey1());
Assertions.assertEquals("complexKey2", configurationDemo.getComplex().getKey2());
}
}
注意事项:
1. 配置类中的@Configuration用于标记此类是一个SpringBean,可以替换为Component等有相同效果的注解
2. 定义复杂配置需要增加类,类似例子中的Complex类
非springboot项目
普通spring项目还需要在配置类上添加@EnableConfigurationProperties
注解,并且可以通过@PropertySource
注解从指定配置文件位置
@Data
@Configuration
@EnableConfigurationProperties
@PropertySource("classpath:application.yaml")
@ConfigurationProperties(prefix = "demo.config")
public class ConfigurationDemo {
private String key1;
private String key2;
private Complex complex = new Complex();
@Data
public class Complex {
private String key1;
private String key2;
}
}
其他知识点
- 在高版本gradle中使用lombok
annotationProcessor "org.projectlombok:lombok:${dpd.lombokVersion}"
compileOnly "org.projectlombok:lombok:${dpd.lombokVersion}"
testAnnotationProcessor "org.projectlombok:lombok:${dpd.lombokVersion}"
testCompileOnly "org.projectlombok:lombok:${dpd.lombokVersion}"