文章来自:https://www.cnblogs.com/warehouse/p/8681187.html的分享
网上记录的方法很多,这里只记录自己所使用的过的其中一种方法,不喜勿喷。
package com.demo.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;@Component
@PropertySource("classpath:application.properties")
public class ConfigUtils {
/**
* @PropertySource 读取配置文件必须返回一个 PropertySourcesPlaceholderConfigurer 的bean,否则会不能识别@Value("${demo}") 注解中的 ${demo}指向的value,
* 而会注入${demo}的字符串,返回 PropertySourcesPlaceholderConfigurer 的方法,使用 @Bean 注解,表示返回的是个bean
* @return
*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Value("${demo}")
private String demo;
public String getDemo() {
return demo;
}public void setDemo(String demo) {
this.demo= demo;
}
}