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

代替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>

由于物流管理系统是一个比较复杂的系统,涉及到很多模块和功能,这里我提供一个简单的示例代码,仅供参考。 1. 配置文件 application.properties ``` # 数据库配置 spring.datasource.url=jdbc:mysql://localhost:3306/logistics?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # Mybatis-plus配置 mybatis-plus.mapper-locations=classpath:mapper/*.xml mybatis-plus.global-config.db-config.logic-delete-field=deleted mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0 ``` 2. 货物管理模块 GoodsController.java ```java @RestController @RequestMapping("/goods") public class GoodsController { @Autowired private GoodsService goodsService; /** * 获取所有货物 */ @GetMapping("/") public ResponseResult<List<Goods>> getAllGoods() { List<Goods> goodsList = goodsService.list(); return new ResponseResult<>(ResponseStatus.SUCCESS, goodsList); } /** * 添加货物 */ @PostMapping("/") public ResponseResult<Void> addGoods(@RequestBody Goods goods) { boolean result = goodsService.save(goods); if (result) { return new ResponseResult<>(ResponseStatus.SUCCESS); } else { return new ResponseResult<>(ResponseStatus.FAILED); } } /** * 修改货物 */ @PutMapping("/") public ResponseResult<Void> updateGoods(@RequestBody Goods goods) { boolean result = goodsService.updateById(goods); if (result) { return new ResponseResult<>(ResponseStatus.SUCCESS); } else { return new ResponseResult<>(ResponseStatus.FAILED); } } /** * 删除货物 */ @DeleteMapping("/{id}") public ResponseResult<Void> deleteGoods(@PathVariable Long id) { boolean result = goodsService.removeById(id); if (result) { return new ResponseResult<>(ResponseStatus.SUCCESS); } else { return new ResponseResult<>(ResponseStatus.FAILED); } } } ``` GoodsService.java ```java public interface GoodsService extends IService<Goods> { } ``` GoodsServiceImpl.java ```java @Service public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService { } ``` GoodsMapper.java ```java public interface GoodsMapper extends BaseMapper<Goods> { } ``` Goods.java ```java @Data public class Goods implements Serializable { private static final long serialVersionUID = 1L; /** * 货物ID */ @TableId(type = IdType.AUTO) private Long id; /** * 货物名称 */ private String name; /** * 货物型 */ private String type; /** * 货物数量 */ private Integer quantity; /** * 货物描述 */ private String description; /** * 创建时间 */ @TableField(fill = FieldFill.INSERT) private Date createTime; /** * 更新时间 */ @TableField(fill = FieldFill.UPDATE) private Date updateTime; /** * 是否删除 */ @TableLogic private Integer deleted; } ``` 3. 订单管理模块、配送管理模块、仓库管理模块和用户管理模块的代码似,这里不再赘述。 以上代码仅供参考,具体实现可以根据实际需求进行调整和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值