1.先引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.新建一个Java类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 常量类
*
*/
@Configuration
// prefix代表属性文件中的前缀
@ConfigurationProperties(prefix = "constant")
// @PropertySource指定加载的那个属性文件,如是默认的application.properties 则不用指定
@PropertySource("classpath:constant.properties")
@Data
public class Constant {
private String name;
private String sex;
}
3.新建constant.properties
constant.name=zhang san
constant.sex=male
使用时,通过依赖注入得到单例
@Autowired
private Constant constant;