spring boot应用程序 - 从静态上下文获取bean

时间:2017-05-05 12:00:33

标签: spring spring-boot

我有一个在Spring之外创建的类的实例,我希望能够访问Spring bean,以便它可以触发一个事件并被Spring bean观察到。我没有使用Spring网络,我的应用程序是通过命令行通过spring boot运行的。

2 个答案:

答案 0 :(得分:7)

您唯一的选择是使用静态方法公开应用程序的Spring上下文,以便Spring不管理的对象可以使用它来获取所需的托管bean的引用。

  1. 从上下文的包装器开始。创建一个常规托管bean,它需要在其构造函数中引用上下文。该引用被分配给一个静态类字段,该字段也有一个静态getter:

    @Service
    class ContextWrapper {
    
        private static ApplicationContext context;
    
        @Autowired
        public ContextWrapper(ApplicationContext ac) {
            context = ac;
        }
    
        public static ApplicationContext getContext() {
            return context;
        }
    
    }
    
  2. 使用静态getter访问不受Spring管理的对象中的上下文,并使用上下文中可用的方法引用bean:

    SomeBean bean = ContextWrapper.getContext().getBean("someBean", SomeBean.class);
    // do something with the bean
    
  3. 您需要的最后一件事是从Spring bean到非托管对象的通信渠道。例如,SomeBean可以公开一个setter,它将接受非托管对象作为参数,并将引用存储在一个字段中以备将来使用。对象mast使用上面提到的静态上下文访问器获取对托管bean的引用,并使用setter使bean知道它的存在。

    @Service
    class SomeBean {
    
        // ... your bean stuff
    
        private SomeClass someclass;
    
        public void setSomeClass(Someclass someclass) {
            this.someclass = someclass;
        }
    
        private void sendEventToSomeClass() {
            // communicate with the object not managed by Spring 
            if (someClass == null) return;
            someClass.sendEvent();
        }
    
    }
    

答案 1 :(得分:-1)

你可以通过构造函数注入spring bean,例如:

@Service
class Bean {
    ...
}

class NotBean {

      private Bean bean;

      public NotBean(Bean bean) {
       this.bean = bean;
      }

      // your stuff (handle events, etc...)
}
相关问题