Parag
Parag

Reputation: 193

where to apply ApplicationContextAware

I have a Service class which is a spring bean and I want to use this Service class inside a class (Class A) which is not a spring bean.

Where exactly should I implement ApplicationContextAware ?

Following is my code

   @Service("sharedListsService")
   public class  SharedListsService
   {

   }

   public class A
   {
      // I want to call my service class methods here
   }

Upvotes: 0

Views: 117

Answers (2)

Martin Špelina
Martin Špelina

Reputation: 51

ApplicationContextAware applies to spring beans only. It will inject application context into a bean. That's why you cannot directly use it to get instance of SharedListsService into "A". You need a bean, possibly a factory for "A" to wire that for you.

Upvotes: 1

Mykyta Lebid
Mykyta Lebid

Reputation: 77

I'm not sure that it is a best solution but you can refactor your A class like following:

public class A {
    private SharedListsService sharedListsService;

    public void setSharedListsService(SharedListsService sharedListsService) {
        this.sharedListsService = sharedListsService;
    }
}

and then inject spring bean when you create an A class instance (for example):

SharedListsService sharedListsService = WebApplicationContextUtils.getWebApplicationContext(appContext).getBean(SharedListsService.class);

A a = new A();
a.setSharedListsService(sharedListsService);

Upvotes: 1

Related Questions