Java 如何从不是由 spring 创建的对象访问 spring bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19302030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:51:23  来源:igfitidea点击:

how to access spring beans from objects not created by spring

javaspringhibernate

提问by Dev Blanked

In my web application i use hibernate and spring. Entity classes that are returned from Hibernate layer need to access other service classes in some scenarios. Entity classes are not just DTO's they contains some business logic, and to perform some business logic (like may be send out emails etc when some conditions are met) these need to access service classes. Service classes are spring beans. so what's the recommended method in such scenarios to get hold of spring beans from within these entity classes which are created outside spring context?

在我的 Web 应用程序中,我使用 hibernate 和 spring。Hibernate 层返回的实体类在某些场景下需要访问其他服务类。实体类不仅仅是 DTO,它们包含一些业务逻辑,并且为了执行一些业务逻辑(例如在满足某些条件时可能会发送电子邮件等),这些需要访问服务类。服务类是 spring bean。那么在这种情况下,从这些在 spring 上下文之外创建的实体类中获取 spring bean 的推荐方法是什么?

回答by Jigar Joshi

You are looking for Service-locatorpattern,

您正在寻找服务定位器模式,

Implementation in Spring

Spring中的实现

You can register ApplicationContextAwareand get reference to ApplicationContextand statically serve bean

您可以注册ApplicationContextAware并获取对ApplicationContextbean 的引用和静态服务 bean

public class ApplicationContextUtils implements ApplicationContextAware {
 private static ApplicationContext ctx;

 private static final String USER_SERVICE = "userServiceBean";

  @Override
  public void setApplicationContext(ApplicationContext appContext)
      throws BeansException {
    ctx = appContext;

  }

  public static ApplicationContext getApplicationContext() {
    return ctx;
  }

  public static UserService getUserService(){return ctx.getBean(USER_SERVICE);}

}

回答by Jose Luis Martin

Read about @Configurableannotation that allows to configure beans using AspectJ:

阅读关于@Configurable允许使用 AspectJ 配置 bean 的注释:

If you don't want to use AspectJ, you could use the

如果你不想使用 AspectJ,你可以使用

ApplicationContext.getAutowireCapableBeanFactory().autowireBean()

ApplicationContext.getAutowireCapableBeanFactory().autowireBean()

method to configure beans that live outside the spring container. (see java docs).

配置驻留在 spring 容器之外的 bean 的方法。(请参阅 Java 文档)。