使用java config 配置spring 和spring mvc

时间:2022-05-25 20:33:52

无xml配置的环境,主要基于java config

  1. 继承AbstractAnnotationConfigDispatcherServletInitializer
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

/**
* 启动器
*
* @param servletContext servletContext
* @throws ServletException ServletException
*/

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//调用父类的方法启动spring
super.onStartup(servletContext);
//自定义的serlvet注册
customizeRegistrationServlet(servletContext);
}

/**
* spring根容器注解扫描,扫描controller之外的包,一些基于java config 的配置类
*/

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{};
}


/**
* 注册自定义的Servlet,listener 等
*
* @param servletContext servletContext
*/

private void customizeRegistrationServlet(ServletContext servletContext) {

}

/**
* 注册 Filter,父类中返回null 子类可以覆盖此方法 ,注册Filter
*
* @return Filter[]
*/

@Override
protected Filter[] getServletFilters() {
return new Filter[]{};
}

/**
* spring mvc 容器启动时的监听
*
* @return ApplicationContextInitializer<?>[]
*/

@Override
protected ApplicationContextInitializer<?>[] getServletApplicationContextInitializers() {
SpringMvcAppInitListener applicationContextInitializer = new SpringMvcAppInitListener();
return new ApplicationContextInitializer[]{applicationContextInitializer};
}

/**
* spring 根容器启动时的监听事件,可以提前初始化一些配置,可以实现
* 区分spring boot 加载不同的配置文件.区分dev . test . prod
*
* @return ApplicationContextInitializer<?>[]
*/

@Override
protected ApplicationContextInitializer<?>[] getRootApplicationContextInitializers() {
SpringRootAppInitListener springRootAppInitListener = new SpringRootAppInitListener();
return new ApplicationContextInitializer[]{springRootAppInitListener};
}

/**
* spring mvc的注解扫描,只扫描controller的包
*/

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{SpringMvcConfig.class};
}

/**
*DispatcherServlet 映射路径,DispatcherServlet 本身就是一个Serlvet
*/

@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}

/**
* DispatcherServlet 配置项
*/

@Override
protected void customizeRegistration(Dynamic registration) {
registration.setInitParameter("dispatchOptionsRequest", "true");
super.customizeRegistration(registration);
}

}

自此整个配置就结束了,下面分析下自定义实现spring boot 基于不同的环境加载不同配置文件.