我有一个遗留应用程序,它对所有服务使用单例模式,并通过ServiceName.getInstance()在使用其他服务的服务内部和web层访问所有服务。我正在将项目转换为使用Spring,并且正在考虑使用getServiceA和getServiceB..etc方法创建一个单例实用程序类ServiceProvider,并让它从Spring应用程序上下文中获取bean。我将只在web层使用ServiceProvider,因为我还不能将它转换为使用Spring,并自动部署所有使用其他服务的服务。这是一个好的解决方案吗?
我有一个非常简单的web层,也许有人可以推荐如何用最少的更改来冲刺它。我有一个在启动时加载的控制器的url映射。RequestDispatcher解析请求url,按类查找控制器并执行模板方法(基本控制器有各种子类,但这不会使问题复杂化)。
RequestDispatcher:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int slashIndex = req.getRequestURL().lastIndexOf("/");
String path = req.getRequestURL().substring(slashIndex, req.getRequestURL().length());
ServiceURL url = urlMap.get(path);
ServiceProvider.getLog().info("Requested page: " + path);
if (url != null) {
try {
Utils.authenticate(req, resp);
grantAccess(req, url);
BaseServlet servlet = (BaseServlet)url.getClass().getClassLoader().loadClass(url.getClassName()).newInstance();
servlet.service(req, resp);
}
catch (AuthorizationException e) {
resp.getWriter().write(new ErrorModel("You are not authorized to perform the requested action.").getContent());
ServiceProvider.getAuthLog().info("auth", e);
}catch (SystemException e) {我正在考虑将我的servlet注释为组件,让包自动扫描。ApplicationContext可以通过完整的类名获取bean吗?
发布于 2013-05-17 00:27:53
看起来你的服务是无状态的。我会用@Service对它们进行注释(让它们成为spring bean),然后在你需要的任何地方@Autowire。让Spring充当服务提供者。
发布于 2013-05-17 01:10:54
您的getInstance()解决方案听起来像是对象不在Spring的控制之下。
如果您需要以JNDI查找的形式访问服务,那么您应该在Spring中这样配置它们。
如果它在Spring的控制之下,就不应该在代码中实例化它。如果它是在你的代码中实例化的,那么它就不在Spring的控制之下。
https://stackoverflow.com/questions/16592162
复制相似问题