I have an object created using a new operator. Is there a way, in Spring, to load this object in the Spring application context?
I did some research but could not find a working solution. Thanks in advance.
//Get hold of application context, you can autowire it
ConfigurableApplicationContext context;
ServiceX servicex = //This object was created outside spring framework.
//Register it with spring
context.getBeanFactory().registerSingleton("servicex", servicex);
//Above bean is now available as part of spring application context.
You can use Spring's @Configuration class and define @Bean method in there. In that method, create your custom new object and make sure you return that object.
@Bean
public YourType methodName() {
//code here..
return new YourType();
}
Put this into your @Configuration class and object returned by return new YourType(); will be registered into your Spring Context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With