【发布时间】:2012-08-09 04:32:43
【问题描述】:
我正在尝试构建一个 Spring 3.1 PropertySource,它从 Zookeeper 节点读取其值。为了连接到 Zookeeper,我使用了来自 Netflix 的 Curator。
为此,我构建了一个自定义属性源,它从 Zookeeper 读取属性的值并返回它。当我像这样解析属性时,这很好用
ZookeeperPropertySource zkPropertySource = new ZookeeperPropertySource(zkClient);
ctx.getEnvironment().getPropertySources().addLast(zkPropertySource);
ctx.getEnvironment().getProperty("foo"); // returns 'from zookeeper'
但是,当我尝试实例化一个带有 @Value 注释的字段的 bean 时,这会失败:
@Component
public class MyBean {
@Value("${foo}") public String foo;
}
MyBean b = ctx.getBean(MyBean.class); // fails with BeanCreationException
这个问题很可能与 Zookeeper 无关,而是与我注册属性源和创建 bean 的方式有关。
高度赞赏任何见解。
更新 1:
我正在从这样的 XML 文件创建应用上下文:
public class Main {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.registerShutdownHook();
}
}
连接到 Zookeeper 的类是 @Component。
@Component
public class Server {
CuratorFramework zkClient;
public void connectToZookeeper() {
zkClient = ... (curator magic) ...
}
public void registerPropertySource() {
ZookeeperPropertySource zkPropertySource = new ZookeeperPropertySource(zkClient);
ctx.getEnvironment().getPropertySources().addLast(zkPropertySource);
ctx.getEnvironment().getProperty("foo"); // returns 'from zookeeper'
}
@PostConstruct
public void start() {
connectToZookeeper();
registerPropertySource();
MyBean b = ctx.getBean(MyBean.class);
}
}
更新 2
当我使用无 XML 配置时,这似乎有效,即 @Configuration、@ComponentScan 和 @PropertySource 与 AnnotationConfigApplicationContext 结合使用。为什么它不适用于 ClassPathXmlApplicationContext?
@Configuration
@ComponentScan("com.goleft")
@PropertySource({"classpath:config.properties","classpath:version.properties"})
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
【问题讨论】:
标签: spring properties apache-zookeeper