在我的Web应用程序中,我使用 hibernate 和 Spring 。在某些情况下,从Hibernate层返回的实体类需要访问其他服务类。实体类不仅是DTO的实体类,还包含一些业务逻辑,并且要执行一些业务逻辑(例如,在满足某些条件时可能会发送电子邮件等),这些都需要访问服务类。服务类是 Spring bean 。那么在这种情况下,从这些实体类(在Spring上下文外部创建)中获取Spring Bean的推荐方法是什么?
最佳答案
您正在寻找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);}
}