Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading manually created object to spring context

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.

like image 483
Umesh Sanwal Avatar asked Oct 20 '25 14:10

Umesh Sanwal


2 Answers

  • If you are creating an object after Spring application has started and you want to register it as bean with spring, you can do it. ie. run time only you will know how it will be created or that object is created by a external framework you don't have control over. I just can't remember the frameworks, there are frameworks that used this facility.
     //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.

like image 103
Kavithakaran Kanapathippillai Avatar answered Oct 23 '25 08:10

Kavithakaran Kanapathippillai


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.

like image 24
Giorgi Tsiklauri Avatar answered Oct 23 '25 07:10

Giorgi Tsiklauri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!