java—如何替换spring batch admin中的homecontroller

8wtpewkr  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(257)

在spring批处理管理环境中,我为“/”和“/主页”使用自定义视图。我不需要所有可用端点的概述。
我想在这本书中再增加一些内容 model 用于视图的。
端点的控制器包含在spring批处理管理中 org.springframework.batch.admin.web.util.HomeController (源代码)。显然,我不能仅仅创建一个自己的控制器并请求Map,因为spring中不允许对同一端点进行双重Map。
这个 HomeController 注解为 @Controller 初始化时自动加载。
我有一个解决方案,这样我在同一个包中有一个自己的类,它比spring batch admin中包含的类具有更高的优先级。然而,这不是我喜欢的,因为它是糟糕的设计imho。
这包括对库的实现的不期望的依赖。另外,我必须实现这两种方法 setDefaultResources 以及 setJsonResources 它们是由批处理管理员以某种方式调用的,而不是接口方法。
我也不知道拥有两个相同类的行为是否在java中得到了很好的定义。
问题:有没有一种简单的方法来避免原来的主控制器被示例化,或者有没有另一种方法将我自己的模型注入到控制器中?

brccelvz

brccelvz1#

当根目录 / 通过拦截器访问。首先,我们必须创建自己的控制器,为我们的登录页创建模型。无法将其Map到 / 或者 /home 因为这些Map已经定义。

public class CustomHomeController {

    @RequestMapping(value = { "/customHome" }, method = RequestMethod.GET)
    public String landingPage(ModelMap model) {
        fill(model);

        // Here "home" refers to a view name e.g. as Freemarker template
        return "home";
    }
}

然后,我们就可以拦截 / 并使用 AsyncHandlerInterceptor :

public class HomeInterceptor extends HandlerInterceptorAdapter {

    /**The controller instance returning the view for the landing page. */
    private final CustomHomeController customHomeController;

    @Autowired
    public HomeInterceptor(CustomHomeController customHomeController) {
        this.customHomeController = customHomeController;
    }

    /**
     * Swaps the {@link ModelAndView} to the one returned by
     * {@link CustomHomeController#landingPage(ModelMap) }.
     * The controller performs no checking if the model and view is
     * actually one for the landing page. The correct setup
     * has to be ensured by the configuration.
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // Manually call the Controller custom home
        // If necessary, also request can be forwarded
        customHomeController.landingPage(modelAndView.getModelMap());
    }
}

在配置中,将注入处理程序:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/"/>
        <bean class="com.example.HomeInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

这需要 xmlns:mvc="http://www.springframework.org/schema/mvc" 以及 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 在架构定义中。
如果需要,可以禁用原始 /home 通过安全配置Map。

相关问题