Autowiring in Spring bean (@Component) created with new keyword

I have two spring beans as follows:

public class A extends TimerTask {

    private CampaignDao campaignDao;
    private CampaignManager campManger;

I have to make a new object of A with new keyword, due to a legacy code

public class B{
     public void test(){
       A a = new A();

when Running -> the spring beans in the class A are null, can i create a new instance of the spring bean A and still use autowiring in it ?


Yours component "A" is not created by Spring container, thus, dependencies are not injected. However, if you need to support some legacy code (as I understand from your question), you can use @Configurable annotation and build/compile time weaving:

@Configurable(autowire = Autowire.BY_TYPE)
public class A extends TimerTask {
  // (...)

Then, Spring will inject autowired dependencies to component A, no matter if it's instantiated by container itself, or if it's instantiated in some legacy code by new.

For example, to set up build-time weaving with maven plugin you have to:

  1. Add <context:spring-configured/> to the Spring application context
  2. Configure Maven AspectJ plugin:

in the build plugins section:

          Xlint set to warning alleviate some issues, such as SPR-6819. 
          Please consider it as optional.


...and the dependencies section:


Please consult Spring reference for more details:

Because you are creating the object of class A yourself using new operator, you are not getting the autowired fields in that object and finding them null. Try to get the bean from spring container.

Hope this helps you. Cheers.

Need Your Help

ASP.NET inline scripting

c# scripting inline

I have a DateTime object that I need to print in a custom gridlike control.

Architecture of Azure Mobile Services Application

.net architecture azure-mobile-services win-universal-app offlineapps

I'm trying to piece together an architecture for a Windows Universal App leveraging Azure Mobile Services. It's a LOB app and will need to handle 100-250 offline\online tables. Currently Mobile Ser...