AbstractApplicationContext.getBean() return null for registered beans thru prepareBeanFactory

StackOverflow https://stackoverflow.com/questions/18822343

質問

I want to define an MBeanServerConnection dynamically in the spring application context, so I am registering its factory thru prepareBeanFactory(). I can see the bean exists in the context, but when I do getBean(), it returns me null!.

Any suggestions?

    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);
    }
}
役に立ちましたか?

解決

Given that you are instantiating the factory bean yourself, you are responsible for initializing it by calling afterPropertiesSet(), which is where the connection is made.

If you register a BeanDefinition instead, the context will take care of initializing it for you.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top