代码之家  ›  专栏  ›  技术社区  ›  nabsha

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

  •  0
  • nabsha  · 技术社区  · 13 年前

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

    有什么建议吗?

        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);
        }
    }
    
    1 回复  |  直到 13 年前
        1
  •  0
  •   Gary Russell    13 年前

    假设您正在自己实例化工厂bean,那么您将负责通过调用 afterPropertiesSet() ,即进行连接的位置。

    如果您注册 BeanDefinition 相反,上下文将负责为您初始化它。