【问题标题】:how to access spring beans from objects not created by spring [duplicate]如何从不是由spring创建的对象访问spring bean [重复]
【发布时间】:2013-10-18 13:59:21
【问题描述】:

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

【问题讨论】:

  • 就我个人而言,我不希望我的 DTO 访问我的服务类,而是将它们作为工作流的一部分提供服务类从 Hibernate 中检索实体。
  • @nicholas.hauschild 这些是丰富的领域对象,因此需要承载业务逻辑。
  • 我已经在这个应用程序上工作过danjee.github.io/hedgehog也许将来会有所帮助

标签: java spring hibernate


【解决方案1】:

您正在寻找Service-locator 模式,

在 Spring 中实现

您可以注册ApplicationContextAware并获取ApplicationContext的引用并静态服务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);}

}

【讨论】:

  • 但是这个实现可能会在 Sonar(代码转换工具)中产生重大错误,因为我们正在从非静态方法设置静态字段。因此,为避免您可能必须创建单独的 AppContext 类,您可以在其中通过静态 getApplicationContext() 方法初始化应用程序上下文并使用静态 setApplicationContext() 设置上下文。从实现 ApplicationContextAware 的类中调用 AppContext 的 set 方法,如下所示@Override public void setApplicationContext(ApplicationContext applicationContext) { AppContext.setApplicationContext(applicationContext); }
【解决方案2】:

阅读@Configurable 注释,它允许使用 AspectJ 配置 bean:

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

ApplicationContext.getAutowireCapableBeanFactory().autowireBean()

配置位于 spring 容器之外的 bean 的方法。 (参见 java 文档)。

【讨论】:

  • AspectJ 是否与最终类和序列化到数据库并存储为 BLOB 的类一起使用?
  • 我收到错误无法从 AbstractApplicationContext 类型对非静态方法 getAutowireCapableBeanFactory() 进行静态引用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
相关资源
最近更新 更多