Spring+SpringMVC+MyBatis-Plus纯配置类 无XML

程和蔼
2023-12-01

代替web.xml

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

/**
 * web.xml
 *
 * @author riko
 * @since 2021-11-05
 */
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

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

    /**
     * 指定mvc的核心配置类
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringConfiguration.class};
    }

    /**
     * 等同于将DispatcherServlet的url-pattern设置为"/"
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * 添加字符过滤器
     */
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        return new Filter[] {characterEncodingFilter};
    }
}


Mysql8.0.22 数据库连接信息  application.properties(放在resources下)

#数据库连接
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf8&useSSL=false&nullCatalogMeansCurrent=true&serverTimezone=Asia/Shanghai

Druid数据源配置类

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 和连接数据库相关的配置类
 *
 * @author riko
 * @since 2021-11-05
 */
public class JdbcConfig {

    @Value("${spring.datasource.driver}")
    private String driver;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    /**
     * 创建数据源对象
     */
    @Bean(name="dataSource")
    public DataSource createDataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        //配置监控统计拦截的filters
        dataSource.setFilters("stat");
        //配置初始化大小、最小、最大
        dataSource.setMaxActive(20);
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        //配置获取连接等待超时的时间
        dataSource.setMaxActive(60000);
        //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        //配置一个连接在池中最小生存的时间,单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        //打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxOpenPreparedStatements(20);
        return dataSource;
    }
}

MyBatisPlus配置类

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 配置核心Mybatis核心工厂
 *
 * @author riko
 * @since 2021-11-05
 */
public class MyBatisPlusConfig {

    @Bean(name="sqlSessionFactoryBean")
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();

        //设置别名
        factoryBean.setTypeAliasesPackage("com.riko.**.bean.*");

        //设置日志
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setLogImpl(Log4j2Impl.class);
        factoryBean.setConfiguration(mybatisConfiguration);

        //设置数据源
        factoryBean.setDataSource(dataSource);


        //设置mapper.xml地址
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/**/*Mapper.xml"));

        return factoryBean.getObject();
    }
}

事务配置类

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * 和事务相关的配置类
 *
 * @author riko
 * @since 2021-11-05
 */
public class TransactionConfig {

    /**
     * 用于创建事务管理器对象
     */
    @Bean(name="transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

}

主配置类

import com.riko.comic.core.converter.LocalDateTimeConverter;
import com.riko.comic.core.exception.CustomHandleException;
import com.riko.comic.core.interceptor.LoginInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.*;
import org.springframework.format.FormatterRegistry;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * spring配置
 *
 * @author riko
 * @since 2021-11-05
 */
@Configuration
@ComponentScan({"com.riko"})
@MapperScan({"com.riko.**.mapper"})
@PropertySource("classpath:application.properties")
@Import({JdbcConfig.class, MyBatisPlusConfig.class, TransactionConfig.class})
@EnableAspectJAutoProxy
@EnableTransactionManagement
@EnableWebMvc
public class SpringConfiguration implements WebMvcConfigurer {

    /**
     * 静态资源处理
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    /**
     * 配置commons-upload上传
     */
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        //设置限制上传大小
        resolver.setMaxUploadSize(104857600);
        //设置编码
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }


    /**
     * 添加拦截器
     * addInterceptor方法指定自定义拦截器对象
     * addPathPatterns方法指定哪些请求经过拦截器
     * excludePathPatterns方法指定哪些请求放行
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/comic/**/chapter/**","/comic/**/comment","/chapterComments/comments/**/comment"
                        ,"/rank/save","/collect/save","/sys/user/person/**");
        //
        //registry.addInterceptor(new RoleInterceptor())
        //        .addPathPatterns("/item/itemEdit","/user/userEdit");
    }

    /**
     * 配置默认的视图解析器
     */
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        //如果页面需要使用JSTL标签库
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    /**
     * 转换器
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new LocalDateTimeConverter());
        WebMvcConfigurer.super.addFormatters(registry);
    }
}

log4j2.xml   日志(放在resources下)

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="Console" />
        </Root>

        <logger name="com.riko.comic.module.**.mapper" level="debug" additivity="false">
            <AppenderRef ref="Console" />
        </logger>
    </Loggers>
</Configuration>

 类似资料: