Dev*_*ked 12 java spring hibernate
在我的Web应用程序中,我使用hibernate和spring.在某些情况下,从Hibernate层返回的实体类需要访问其他服务类.实体类不只是DTO,它们包含一些业务逻辑,并且为了执行某些业务逻辑(例如,当满足某些条件时可能发送电子邮件等),这些需要访问服务类.服务类是spring bean.那么在这种场景中推荐的方法是什么,以便在Spring环境之外创建的这些实体类中获取spring bean?
Jig*_*shi 15
您正在寻找服务定位器模式,
在Spring中实现
您可以注册ApplicationContextAware并获取对ApplicationContextbean的静态服务
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);}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12043 次 |
| 最近记录: |