Spring: embedding an object that runs ApplicationContext in ApplicationContext

I want to use Spring inside an outdated application.

The core is a class, let it be called LegacyPlugin, which is a kind of insert in the application. The problem is that this class is also a database connector and is used to create many other objects, often using the built-in constructor ...

I want to run ApplicationContext from LegacyPlugin and embed it in ApplicationContext using BeanFactory, for example, to create other objects. Then the code will be rewritten to use setter injection, etc.

I would like to know what is the best way to achieve this. So far I have a working version using BeanFactory that uses ThreadLocal to store a static link to the current plugin, but it seems ugly to me ...

Below is the code I would like:

public class MyPlugin extends LegacyPlugin { public void execute() { ApplicationContext ctx = new ClassPathXmlApplicationContext(); // Do something here with this, but what ? ctx.setConfigLocation("context.xml"); ctx.refresh(); } } 

 <!-- This should return the object that launched the context --> <bean id="plugin" class="my.package.LegacyPluginFactoryBean" /> <bean id="someBean" class="my.package.SomeClass"> <constructor-arg><ref bean="plugin"/></constructor-arg> </bean> <bean id="someOtherBean" class="my.package.SomeOtherClass"> <constructor-arg><ref bean="plugin"/></constructor-arg> </bean> 
+4
source share
2 answers

Actually, this does not work ... This causes the following error:

 BeanFactory not initialized or already closed call 'refresh' before accessing beans via the ApplicationContext 

The ultimate solution is to use a GenericApplicationContext :

 GenericApplicationContext ctx = new GenericApplicationContext(); ctx.getBeanFactory().registerSingleton("plugin", this); new XmlBeanDefinitionReader(ctx).loadBeanDefinitions( new ClassPathResource("context.xml")); ctx.refresh(); 
0
source

The SingletonBeanRegistry interface allows you to manually enter a pre-configured singleton into a context through its registerSingleton method, for example:

 ApplicationContext ctx = new ClassPathXmlApplicationContext(); ctx.setConfigLocation("context.xml"); SingletonBeanRegistry beanRegistry = ctx.getBeanFactory(); beanRegistry.registerSingleton("plugin", this); ctx.refresh(); 

This adds a plugin bean to the context. You do not need to declare it in the context.xml file.

+4
source

Source: https://habr.com/ru/post/1345778/


All Articles