Issue
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);
}
}
Solution
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.
Answered By - Gary Russell
Answer Checked By - Katrina (JavaFixing Volunteer)