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"));
context.register(AppSpringConfig.class);
context.refresh();

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

One thought on “Add an existing bean/object to a Spring ApplicationContext using JavaConfig

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s