自定义spring属性源不解析@Value中的占位符

自定义spring属性源不解析@Value中的占位符,第1张

概述我正在尝试构建一个Spring 3.1 PropertySource,它从Zookeeper节点读取它的值.为了连接到Zookeeper,我使用的是Netflix的Curator.为此,我构建了一个自定义属性源,它从Zookeeper读取属性的值并返回它.当我解析这样的属性时,这很好用ZookeeperPropertySource zkPropertySou

我正在尝试构建一个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时,这会失败:

@Componentpublic 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.

@Componentpublic 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();    }}
最佳答案回答您的更新2:这不适用于您的原始配置(使用@postconstruct注册PropertySource),因为PropertySource注册很晚,此时您的目标bean已经构建并初始化.

通常,占位符的注入是通过BeanFactoryPostProcessor进行的,这是在Spring生命周期的早期(在此阶段尚未创建bean),如果在该阶段注册了PropertySource,则应解析占位符.

最好的方法是使用ApplicationContextInitializer,获取applicationContext的句柄并在那里注册propertySource:

public class CustomInitializer implements ApplicationContextinitializer
总结

以上是内存溢出为你收集整理的自定义spring属性源不解析@Value中的占位符全部内容,希望文章能够帮你解决自定义spring属性源不解析@Value中的占位符所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248519.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)