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

时间:2013-10-10 17:08:54

标签: java spring hibernate

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

2 个答案:

答案 0 :(得分:14)

您正在寻找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);}

}

答案 1 :(得分:4)

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

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

ApplicationContext.getAutowireCapableBeanFactory().autowireBean()

配置位于spring容器外部的bean的方法。 (参见java docs)。