我有一个Spring类的Service类,并且我想在不是Spring bean的类(Class A)中使用此Service类。

我到底应该在哪里实现ApplicationContextAware?

以下是我的代码

   @Service("sharedListsService")
   public class  SharedListsService
   {

   }

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

最佳答案

我不确定这是否是最佳解决方案,但您可以像下面这样重构您的A类:

public class A {
    private SharedListsService sharedListsService;

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


然后在创建A类实例时注入spring bean(例如):

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

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

10-05 21:10