Java config 方式配置SSM,(零xml方式配置)-------小记(1)

一、maven的pom.xml配置:

引入各种jar包,当前项目中用的spring 5.0.5、mysql-connect-java 为6.0.6,所有都maven repository中最新的版本。

项目目录结构图:

Java config 方式配置SSM,(零xml方式配置)-------小记(1)_第1张图片

 

二、spring MVC的配置:

1此配置相当于是web.xml,继承AbstractAnnotationConfigDispatcherServletInitializer类:
 
  
package com.io.ssm.framework.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @author lvyongb.
 * @Description 项目启动初始化类  相当于web.xml
 * @date 2018/4/26.
 *
 */
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    private static final Logger LOG = LoggerFactory.getLogger(WebAppInitializer.class);

    /**
     * spring 根容器
     * @return
     */
    @Override
    protected Class[] getRootConfigClasses() {
        LOG.info("------root配置类初始化------");
        return new Class[] {RootConfig.class};
    }

    /**
     * Spring mvc容器
     * @return
     */
    @Override
    protected Class[] getServletConfigClasses() {
        LOG.info("------web配置类初始化------");
        return new Class[] {WebMvcConfig.class};
    }

    /**
     * DispatcherServlet映射,"/"开始
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        LOG.info("------映射根路径初始化------");
        return new String[] {"/"};
    }

}

2、配置RootConfig,相当于是配置spring的主容器:

 
  
package com.io.ssm.framework.config;

import com.io.ssm.framework.config.DruidDataSourceConfig;
import com.io.ssm.framework.spring.utils.context.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author lvyongb.
 * @Description spring 容器配置
 * @date 2018/4/26.
 */
@Configuration
@Import({DruidDataSourceConfig.class})
@ComponentScan(basePackages = {"com.io.ssm.module"},
        excludeFilters =//不扫描以下包
                {@ComponentScan.Filter(
                        type = FilterType.ANNOTATION,
                        value = {EnableWebMvc.class, ControllerAdvice.class, Controller.class})})
public class RootConfig {

    private static final Logger LOG = LoggerFactory.getLogger(RootConfig.class);

    @Bean
    public BeanNameAutoProxyCreator proxyCreator(){
        BeanNameAutoProxyCreator proxyCreator = new BeanNameAutoProxyCreator();
        proxyCreator.setProxyTargetClass(true);
        proxyCreator.setBeanNames("*Service");
        proxyCreator.setInterceptorNames("transactionInterceptor");
        return proxyCreator;
    }

    @Bean
    public SpringContextUtil springContextUtil() {
        return new SpringContextUtil();
    }
}

 3、配置WebMvcConfig,(springmvc的配置):

 
  
 
  
package com.io.ssm.framework.config;

import com.io.ssm.framework.config.ThymeleafConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.http.CacheControl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author lvyongb.
 * @Description spring mvc 容器配置
 * @date 2018/4/26.

 */
@Configuration  //标识这是一个Java配置类
@EnableWebMvc  //注解用于启动Spring MVC特性
@Import({ThymeleafConfig.class})   //用于引入其他配置类
@ComponentScan(basePackages = {"com.io.ssm.module"},
        includeFilters = //在主容器中排出了,这里需要添加扫描
                {@ComponentScan.Filter(
                        type = FilterType.ANNOTATION,
                        value = {ControllerAdvice.class, Controller.class})})
public class WebMvcConfig implements WebMvcConfigurer {
//public class WebMvcConfig extends WebMvcConfigurationSupport{

    private static final Logger LOG = LoggerFactory.getLogger(WebMvcConfig.class);

    /**
     * 启用spring mvc 的注解(不启用只能通过显示的配置)
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    /**
     * 配置静态资源的映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        LOG.info("-------------加载静态资源-----------------");

        String[] pathPatterns = new String[]{
                "/static/img/**","/static/js/**","/static/i/**","/static/fonts/**","/static/css/**",
                "/static/html/**","/**/*.html"
        };
        String[] resourceLocations = new String[]{
                "/static/img/","/static/js/","/static/i/","/static/fonts/","/static/css/",
                "/static/html/","/"
        };
        registry.addResourceHandler(pathPatterns).addResourceLocations(resourceLocations)
                .setCacheControl(CacheControl.maxAge(31536000, TimeUnit.MILLISECONDS).cachePublic());
    }

    /**
     * 配置项目启动加载的首页
     * @param registry
     */
    @Override
    public void addViewControllers( ViewControllerRegistry registry ) {
        //采用转发的方式
        //registry.addViewController( "/" ).setViewName( "forward:/home" );
        //直接返回页面的方式
        registry.addViewController( "/" ).setViewName( "home" );
        registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
        //super.addViewControllers( registry );
    }
}

注:在配置springmvc的时候,由于在此项目中引入的spring 5.0,而在5.0中WebMvcConfigurerAdapter已过时,不推荐使用,
所以这里我们直接实现接口WebMvcConfigurer即可。

 4、配置视图,采用thymeleaf为模板:

package com.io.ssm.framework.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

/**
 * @author lvyongb.
 * @Description thymeleaf模板配置
 * @date 2018/4/26.
 *
 * ps:这里需要ApplicationContext
 * 解决方法2种:
 * 1、实现ApplicationContextAware接口,重写setApplicationContext方法
 * 2ITemplateResolver templateResolver()定义为一个bean
 */
@Configuration
public class ThymeleafConfig /*implements ApplicationContextAware*/ {

    private static final Logger LOG = LoggerFactory.getLogger(ThymeleafConfig.class);

    /*private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }*/

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        // 设置编码,否则中文乱码
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    @Bean
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        //resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setSuffix(".html");
        //默认是TemplateMode.HTML
        resolver.setTemplateMode(TemplateMode.HTML);
        // 设置编码,否则中文乱码
        resolver.setCharacterEncoding("UTF-8");
        //设置缓存,默认是true
        resolver.setCacheable(true);
        return resolver;
    }

}

然后再WebMvcConfig配置类中通过 @Import ({ThymeleafConfig. class }) 方式引入thymeleaf配置类即可。


https://blog.csdn.net/ly91526188/article/details/80110279

你可能感兴趣的:(Java config 方式配置SSM,(零xml方式配置)-------小记(1))