gpt4 book ai didi

java - Spring框架抽象

转载 作者:行者123 更新时间:2023-11-30 04:22:52 28 4
gpt4 key购买 nike

我有一个遗留应用程序,它对所有服务使用单例模式,并通过使用其他服务和 Web 层的服务内部的 ServiceName.getInstance() 访问所有服务。我正在将项目转换为使用 Spring,并考虑使用方法 getServiceA、getServiceB..etc 创建一个单例实用程序类 ServiceProvider,并让它从 Spring 应用程序上下文获取 bean。我只会在 Web 层使用 ServiceProvider,因为我还无法转换为使用 Spring 并 Autowiring 使用其他服务的所有服务。这是一个好的解决方案吗?

我有一个非常简单的网络层,也许有人可以推荐如何通过最小的更改来 Spring 化它。我有一个在启动时加载的 Controller 的 url 映射。 RequestDispatcher 解析请求 url,按类查找 Controller 并执行模板方法(基本 Controller 有各种子类,但它不会使问题复杂化)。

请求调度程序:

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吗?

最佳答案

看起来您的服务是无状态的。我会用@Service(使它们成为spring beans)注释它们,然后在您需要的任何地方@Autowire它们。让Spring充当服务提供者。

关于java - Spring框架抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16592162/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com