1. 将配置文件中的key作为对象的属性进行读取
test.properties进行读取

创建一个类对应配置文件中的key
@Component
@Data
@PropertySource("test.properties")
@ConfigurationProperties(prefix="obj")
public class ObjectProperties {
private String name;
private int age;
}
@Data注解添加可以不用在写get/set方法
在controller中使用配置文件中的配置信息
@Autowired
private ObjectProperties objectProperties;
@ResponseBody
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test() throws Exception {
return "name : " + objectProperties.getName() + " age : " + objectProperties.getAge();
}

2. 通过流的方式对test.properties进行修改,读取
读取:
/**
* @Title: getProfileByClassLoader
* @Description: 采用ClassLoader(类加载器)方式进行读取配置信息
* @return Map<String,Object> 以Map键值对方式返回配置文件内容
* @param fileName 配置文件名称
* 优点:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
* 缺点:只能加载类classes下面的资源文件
*/
public static Map<String, Object> getProfileByClassLoader(String fileName) {
// 通过ClassLoader获取到文件输入流对象
InputStream in = Profile.class.getClassLoader().getResourceAsStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Properties props = new Properties();
Map<String, Object> profileMap = new HashMap<String, Object>();
try {
props.load(reader);
for (Object key : props.keySet()) {
profileMap.put(key.toString(), props.getProperty(key.toString()));
}
} catch (IOException e) {
e.printStackTrace();
}
return profileMap;
}
修改:
/**
* 传递键值对的Map,更新properties文件
* @param fileName 文件名(放在resource源包目录下),需要后缀
* @param keyValueMap 键值对Map
*/
public static void updateProperties(String fileName, Map<String, String> keyValueMap) throws Exception {
//获取文件路径
String filePath = Profile.class.getClassLoader().getResource(fileName).toURI().getPath();
System.out.println("propertiesPath:" + filePath);
Properties props = new Properties();
BufferedReader br = null;
BufferedWriter bw = null;
try {
// 从输入流中读取属性列表(键和元素对)
br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
props.load(br);
br.close();
// 写入属性文件
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
// 清空旧的文件
// props.clear();
for (String key : keyValueMap.keySet()) {
props.setProperty(key, keyValueMap.get(key));
}
props.store(bw, "改变数据");
bw.close();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Visit " + filePath + " for updating " + "" + " value error");
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3 定时任务的定时表达式从配置文件中读取
3.1 在类前面添加 @PropertySource("classpath:test.properties")
3.2 在定时执行方法签添加 @Scheduled(cron = "${cron.expression}") 使用@Scheduled注解的方法 参数应该设置为空 @Scheduled(cron = "${cron.expression}")
public String ScheduledMethod(){}
3.3 在test.properties中添加
cron.expression=* */2 * * * ?
本文介绍如何在Java中通过Spring Boot框架读取配置文件的属性,并应用于对象实例化及定时任务的配置。详细解释了使用@Component、@Data、@PropertySource和@ConfigurationProperties等注解来读取配置文件,以及通过ClassLoader读取和修改配置文件的方法。
1906

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



