1、ConfigurationProperties
需要在主类添加注解
@EnableConfigurationProperties(PropertiesLoadConfig.class)
@Component
@ConfigurationProperties(prefix = "com.yu.springboot")
@PropertySource("classpath:settingconfig.properties")
public class PropertiesLoadConfig {
private String author;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
2、
@Component
@PropertySource("classpath:settingconfig.properties")
public class PropertiesLoadConfig2 {
@Value("${com.yu.springboot.author}")
private String author;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
3、 静态配置
public class SettingConst {
public static String author;
static {
PropertiesUtils.setProperties(SettingConst.class,"src/main/resources/settingconfig2.properties");
}
}
public class PropertiesUtils {
public static Properties getConfig(String name){
Properties properties = null;
try{
properties = new Properties();
// InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(name);
File file = ResourceUtils.getFile(name);
InputStream is = new FileInputStream(file);
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
properties.load(bf);
is.close();
}catch (Exception ex){
ex.printStackTrace();
}
return properties;
}
/**
* 读取配置参数,赋值到静态属性中
* @param c
* @param path
*/
public static void setProperties(Class c,String path){
Properties properties = getConfig(path);
Field[] fields = c.getFields();
for (Field f: fields
) {
f.setAccessible(true);
try {
f.set(null,properties.getProperty(f.getName()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
本文介绍了三种在Spring Boot中加载配置文件的方法:使用@ConfigurationProperties、@Value和静态配置。通过实例展示了如何从properties文件中读取配置并应用于Java类。
2510

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



