首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AbstractApplicationContext.getBean()为通过prepareBeanFactory注册的bean返回null

AbstractApplicationContext.getBean()为通过prepareBeanFactory注册的bean返回null
EN

Stack Overflow用户
提问于 2013-09-16 07:16:58
回答 1查看 2.4K关注 0票数 0

我希望在spring应用程序上下文中动态定义一个MBeanServerConnection,因此我将通过prepareBeanFactory()注册它的工厂。我可以看到bean存在于上下文中,但是当我执行getBean()时,它会返回null!

有什么建议吗?

代码语言:javascript
复制
    public static void main(String[] args) throws IOException, Exception, IntrospectionException, MalformedObjectNameException, ReflectionException {
    final AbstractApplicationContext context = new ClassPathXmlApplicationContext() {
        protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.prepareBeanFactory(beanFactory);
            final MBeanServerConnectionFactoryBean clientConnection = new MBeanServerConnectionFactoryBean();
            try {
                clientConnection.setServiceUrl("service:jmx:jmxmp://" + "localhost:7777");
                beanFactory.registerSingleton("clientConn", clientConnection);
            } catch (MalformedURLException e) {

            }
        }
    };
    context.refresh();
    for (String name : context.getBeanNamesForType(Object.class)) {
        System.out.println(name);
    }
    MBeanServerConnection mb = context.getBean("clientConn", MBeanServerConnection.class);
    for (String s : mb.getDomains()) {
        System.out.println(s);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-16 13:16:58

假设您自己正在实例化工厂bean,那么您将负责通过调用afterPropertiesSet()来初始化它,这就是连接的位置。

如果您注册了一个BeanDefinition,上下文将负责为您初始化它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18822343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档