将公共的配置抽取出来,写在配置类中,以便后期的维护
- 首先创建一个Springboot项目
- 在resources文件夹下创建一个
config.properties
(文件名随意)文件,在这个文件中配置要抽取的公共配置
方式一 - 写一个读取配置类
package com.lemon.common;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
@PropertySource("classpath:config.properties")
@ConfigurationProperties(prefix = "config")
public class CommonConfig {
private String name;
private Integer age;
}
@Data : 简化get/set方法
@Component : 注入spring管理
@PropertySource(“classpath:config.properties”) : 指定配置文件地址和文件名
@ConfigurationProperties(prefix = “config”) 指定该配置项在配置文件中的前缀
方式二
package com.lemon.common;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author Zhm
* @date 2021/5/16 10:36
**/
@Data
@Component
@PropertySource("classpath:config.properties")
public class CommonConfig {
@Value("${config.name}")
private String name;
@Value("${config.age}")
private Integer age;
}
@Value(${}) : 根据这个{里面给的名字去properties文件中获取对应的值}
两种方式的区别
4.测试类获取
import com.lemon.common.CommonConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Slf4j
class ParcticeApplicationTests {
@Autowired
CommonConfig commonConfig;
@Test
void contextLoads() {
log.info(commonConfig.getName());
log.info(commonConfig.getAge()+"");
}
}
结果显示
可以获取到对应的值