[英]Loading Spring Properties in spring boot
我正在尝试创建一个包含在Spring Boot中存储在属性文件中的值的类
到目前为止,我已经设置了属性为“ source.Ip”的sample.properties文件。
该类如下:
@PropertySource({"classpath:sample.properties"})
@Configuration
@Component
public class PropertyLoader {
@Value("${source.Ip}")
private String sourceIp;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public String getSourceIP(){
return sourceIp;
}
}
该属性文件直接位于src / main / resources下,它是一个源文件夹。
但是我得到了:
java.lang.IllegalArgumentException: Could not resolve placeholder 'source.Ip' in string value "${source.Ip}"
对于我的主要课程,简单如下:
@Configuration
@EnableAutoConfiguration
public class AppStarter {
public static void main(String args[]){
System.out.println(SpringApplication.run(AppStarter.class, args).getBean(PropertyLoader.class).getSourceIP());
}
@Bean
public PropertyLoader propertyLoader(){
return new PropertyLoader();
}
}
sample.properties内容:
source.Ip=127.0.0.1
为了使用PropertySource
属性来解析<bean>
定义或@Value
批注中的${...}
占位符,必须注册PropertySourcesPlaceholderConfigurer
。 在XML
使用<context:property-placeholder>
时,这会自动发生,但是在使用@Configuration
类时,必须使用静态@Bean
方法显式注册。
对于PropertySourcesPlaceholderConfigurer
该方法必须是静态的,因为BeanFactoryPostProcessor (BFPP)
对象必须在容器生命周期的很早之前实例化,因此它们可能会干扰@Configuration
类中对@Configuration
@Autowired
, @Value
和@PostConstruct
之类的批注的处理。
将其添加到您的应用程序类应该可以解决问题:
@Bean
public static PropertySourcesPlaceholderConfigurer pspc() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
return pspc;
}
来自PropertySource文档 。
编辑
你有没有尝试
PropertySourcesPlaceholderConfigurer
放在AppStarter
类中。 PropertySource
批注移动到AppStarter
类。 PropertyLoader
上的Configuration
批注。 该问题可能与PropertyLoader
是组件和配置类这一事实有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.