Java 属性资源占位符配置器和@Configuration
我试图在春季更好地理解配置。我已经阅读了一些示例和教程,但到目前为止,正在发生的事情仍然有些神秘,例如: 废话。属性:Java 属性资源占位符配置器和@Configuration,java,spring,spring-boot,Java,Spring,Spring Boot,我试图在春季更好地理解配置。我已经阅读了一些示例和教程,但到目前为止,正在发生的事情仍然有些神秘,例如: 废话。属性: blah.url=127.0.0.1:2181 Blah.java package com.blah.test; [...] @SpringBootApplication @ComponentScan(basePackages="com.blah.test") public class BlahApp { public static void main(Stri
blah.url=127.0.0.1:2181
Blah.java
package com.blah.test;
[...]
@SpringBootApplication
@ComponentScan(basePackages="com.blah.test")
public class BlahApp {
public static void main(String[] args) {
SpringApplication.run(BlahApp.class, args);
}
}
package com.blah.test;
[...]
@Configuration
@PropertySource(value="classpath:blah.properties")
public class BlahConfig {
private static Log log = LogFactory.getLog(BlahConfig.class);
@Bean
public static PropertySourcesPlaceholderConfigurer
configurer(
Environment environment,
@Value("${blah.url}") String url
) {
String s = environment.resolvePlaceholders("${blah.url}");
log.info("blah url: "+s+" / "+url);
return new PropertySourcesPlaceholderConfigurer();
}
}
BlahConfig.java
package com.blah.test;
[...]
@SpringBootApplication
@ComponentScan(basePackages="com.blah.test")
public class BlahApp {
public static void main(String[] args) {
SpringApplication.run(BlahApp.class, args);
}
}
package com.blah.test;
[...]
@Configuration
@PropertySource(value="classpath:blah.properties")
public class BlahConfig {
private static Log log = LogFactory.getLog(BlahConfig.class);
@Bean
public static PropertySourcesPlaceholderConfigurer
configurer(
Environment environment,
@Value("${blah.url}") String url
) {
String s = environment.resolvePlaceholders("${blah.url}");
log.info("blah url: "+s+" / "+url);
return new PropertySourcesPlaceholderConfigurer();
}
}
如果没有任何设置,这将(部分地)很好地完成所有操作,因此,如果没有任何设置,环境将解析为“127.0.0.1:2181”,我可以从环境变量和/或系统属性重写它
到目前为止还不错。但我希望@Value
注释也能得到同样的结果。没有-为什么没有
还有。。。我假设@Configuration
类中的静态方法是首先要实例化的对象之一,如果它们扩展BeanFactoryPostProcessor
,显然更是如此。在弄清楚东西被初始化的确切顺序时,似乎存在巨大的潜在混淆。有没有人知道我必须在哪些部分打开日志,以便更好地了解订购的时间和原因
谢谢
@Value
是在@PropertySource
之前处理的,而且您的构造至少是可疑的。另外,在使用Spring Boot时,为什么不使用默认的application.properties
,自己处理其他文件呢。利用你所使用的工具,而不是在它们周围进行黑客攻击。我是第一次尝试,但它的行为并不完全符合预期。所以我怀疑这是一个误会,并试图把它搞乱,主要是为了了解那里发生了什么。但是,我也不完全确定application.properties是否总是正确的方法?明确地我正在研究使用zookeeper之类的工具来查找配置。另外,为什么@Value要在@PropertySource之前处理?有什么原因吗?@Bean
是一种工厂方法,它与@Value
注释一样,都是在很早的时候处理的。调用该方法时,将注入/使用环境
,但此时已使用加载的@PropertySource
修改了该环境。