Add an existing bean/object to a Spring ApplicationContext using JavaConfig

Here’s a (very) little post to demonstrate how to add a pre constructed instance to Spring in order to make it known by the ApplicationContext. Then you can inject it into any classic Spring-managed bean.

When would it be usefull ? Imagine you have a legacy application not using Spring. A new feature of this app uses Spring and needs to call methods of an object created by the legacy part (and thus unmanaged by spring). If you use the old XML Spring config, there are numerous exemples on the net. If you want to use the shiny new Javaconfig way, you may have a hard time figuring out how despite you know it must be so simple. Yes it is and here’s how:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getBeanFactory().registerSingleton("myBeanName", new String("String handled as Singleton in Spring"));

This is the simplest way I found. Then up to you to autowire this “legacy” bean in you brand new Spring managed code !