SSM整合-配置类版

目录

  • 一、导入依赖
  • 二、SSM整合
    • 1.1 WebInit配置类
    • 1.2 SpringMvcConfig配置类
    • 1.3 SpringConfig配置类
    • 1.4 JdbcConfig配置类
    • 1.5 MybatisConfig配置类
    • 1.6 mybatis-config.xml配置
    • 1.7 log4j.xml配置
    • 1.8 目录结构

一、导入依赖

  <properties>
    <spring.version>5.3.1spring.version>
  properties>
  <dependencies>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.7version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>2.0.6version>
    dependency>
    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.0.9version>
    dependency>
    
    <dependency>
      <groupId>junitgroupId>I
      <artifactId>junitartifactId>
      <version>4.12version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.16version>
    dependency>
    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>
    
    <dependency>
      <groupId>com.github.pagehelpergroupId>
      <artifactId>pagehelperartifactId>
      <version>5.2.0version>
    dependency>
    
    <dependency>
      <groupId>ch.qos.logbackgroupId>
      <artifactId>logback-classicartifactId>
      <version>1.2.3version>
    dependency>
    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.12.1version>
    dependency>
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.1version>
    dependency>
    
    <dependency>
      <groupId>org.thymeleafgroupId>
      <artifactId>thymeleaf-spring5artifactId>
      <version>3.0.12.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>1.18.20version>
      <scope>providedscope>
    dependency>
  dependencies>

二、SSM整合

1.1 WebInit配置类

此文件代替了web.xml

/*
* 此配置类代替了web.xml配置文件
*
* */
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    //设置一个配置类代替Spring的配置文件
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
    //设置一个配置类代替SpringMvc的配置文件
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }
    //设置SpringMVC的前端控制器Dispatcherservlet的url-pattern
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    //设置当前的过滤器

    @Override
    protected Filter[] getServletFilters() {
        //创建编码过滤器
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter("UTF-8",true);
        //创建处理请求方式的过滤器
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();

        return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter};
    }
}

1.2 SpringMvcConfig配置类

此文件代替了springmvc.xml
前后端分离项目可以不用配置视图解析器和模板引擎

/*
 * 此文件代替了springmvc的配置文件
 * 扫描组件、视图解析器、默认的servlet. mvc 的注解驱动
视图控制器、文件上传解析器、拦截器、异常解析器
 * */
//将类标识为配置类
@Configuration
//扫描组件
@ComponentScan({"com.lx.controller","com.lx.config"})
//开启mvc注解驱动
@EnableWebMvc
//@Order(2)
public class SpringMvcConfig implements WebMvcConfigurer {
    //默认的servlet处理静态资源
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    //设置视图控制器
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    //配置文件上传解析器
    @Bean//@Bean注解可以将标识的方法的返回值作为bean进行管理,bean的id为方法的方法名
    public CommonsMultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }

    //配置拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        FirstInterceptor firstInterceptor = new FirstInterceptor();
        registry.addInterceptor(firstInterceptor).addPathPatterns("/**");
    }

    //配置异常处理器
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
        Properties prop = new Properties();
        prop.setProperty("java.lang.ArithmeticException", "error");
        simpleMappingExceptionResolver.setExceptionMappings(prop);
        simpleMappingExceptionResolver.setExceptionAttribute("ex");
        resolvers.add(simpleMappingExceptionResolver);
    }

    //配置生成模板解析器
    @Bean
    public ITemplateResolver templateResolver(WebApplicationContext webApplicationContext) {
        //ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过WebApplicationContext的方法获得
        ServletContextTemplateResolver templateResolver =
                new ServletContextTemplateResolver(webApplicationContext.getServletContext());
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }
    //生成模板引擎并为模板引擎注入模板解析器
    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }
    //生成视图解析器并为解析器注入模板引擎
    @Bean
    public ViewResolver viewResolver (SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver() ;
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver ;
    }

}

1.3 SpringConfig配置类

此文件用代替了spring.xml

@Configuration
//扫描除控制层组件
@ComponentScan(value = "com.lx",excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class})
})
//开启事务管理
@EnableTransactionManagement
//导入jdbc配置文件
@PropertySource("classpath:jdbc.properties")
//导入配置类
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {
}

1.4 JdbcConfig配置类

此文件用来创建Druid数据源以及事务注解驱动

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    //配置数据源
    @Bean
    public DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    //开启事务管理注解驱动
    @Bean
    public PlatformTransactionManager transactionManager(DruidDataSource dataSource){
        DataSourceTransactionManager dst = new DataSourceTransactionManager(dataSource);
        return  dst;
    }
}

1.5 MybatisConfig配置类

此文件用来配置mybatis

public class MybatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DruidDataSource dataSource,WebApplicationContext webApplicationContext){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setConfigLocation(webApplicationContext.getResource("classpath:mybatis-config.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.lx.pojo");
        //设置分页插
        PageInterceptor pageInterceptor = new PageInterceptor();
        sqlSessionFactoryBean.setPlugins(pageInterceptor);
        return sqlSessionFactoryBean;
    }
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setBasePackage("com.lx.mapper");
        return scannerConfigurer;
    }
}

1.6 mybatis-config.xml配置


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>
configuration>

1.7 log4j.xml配置


DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
        layout>
    appender>
    <logger name="java.sql">
        <level value="debug" />
    logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    root>
log4j:configuration>

1.8 目录结构

SSM整合-配置类版_第1张图片

你可能感兴趣的:(后端相关,SSM)