文章來自: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;
}
}