Spring+SpringMVC+Mybatis JAVA配置

前言

近来公司项目进入测试阶段,得以空闲,于是学习了一下spring。虽然我一直从事前端工作,但是学习一下后端的知识总是不错的。

搭建环境

  • 开发环境:IntelliJ IDEA
  • JDK版本:1.8
  • 依赖包管理工具:gradle
  • 数据库:MYSQL

正文

工程目录

在这里插入图片描述

依赖配置

在工程目录下的build.gradle文件里配置:

dependencies {
    compile(group: 'org.springframework',name: 'spring-core',version: '5.2.2.RELEASE')
    compile(group: 'org.springframework',name: 'spring-context',version: '5.2.2.RELEASE')
    compile(group: 'org.springframework',name: 'spring-beans',version: '5.2.2.RELEASE')
    compile(group: 'org.springframework',name: 'spring-aop',version: '5.2.1.RELEASE')
    compile(group: 'org.springframework',name: 'spring-web',version: '5.2.2.RELEASE')
    compile(group: 'org.springframework',name: 'spring-webmvc',version: '5.2.2.RELEASE')
    compile(group: 'org.springframework',name: 'spring-orm',version: '5.2.2.RELEASE')
    runtime(group: 'org.springframework',name: 'spring-jdbc',version: '5.2.2.RELEASE')
    testCompile(group: 'org.springframework',name: 'spring-test',version: '5.2.2.RELEASE')
    compile group: 'org.mybatis', name: 'mybatis', version: '3.5.3'
    compile group: 'org.mybatis', name: 'mybatis-spring', version: '2.0.3'
    compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.18'
    compile group: 'com.alibaba', name: 'druid', version: '1.1.21'
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1'
    compile(group: 'org.slf4j',name: 'slf4j-api',version: '2.0.0-alpha1')
    compile(group: 'ch.qos.logback',name: 'logback-core',version: '1.3.0-alpha5')
    compile(group: 'ch.qos.logback',name: 'logback-classic',version: '1.3.0-alpha5')
    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.6.0-M1'
}

配置servlet

  • 创建WebAppInitializer类,代码如下:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootContextConfig.class,DruidDataSourceConfig.class};
    }

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

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

类WebAppInitializer相当于web.xml,可以继承AbstractAnnotationConfigDispatcherServletInitializer类,也可以实现WebApplicationInitializer接口详情
RootContextConfig类是与spring相关的配置;DruidDataSourceConfig类是数据库连接配置,这里使用的数据源是阿里的druid;WebMvcConfig类是与试图相关的配置。

  • RootContextConfig类
@Configuration
@ComponentScan(basePackages = "org.iris.api",excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {EnableWebMvc.class, RestController.class})})
public class RootContextConfig {
}
  • DruidDataSourceConfig类
@Configuration
@PropertySource(value = "classpath:/jdbc/druid.properties",ignoreResourceNotFound = true,encoding = "UTF-8")
@MapperScan(basePackages = "org.iris.api.dao")
public class DruidDataSourceConfig {
      @Value("${jdbc.driver}")
      private String driverClass;

      @Value("${jdbc.url}")
      private String jdbcUrl;

      @Value("${jdbc.user}")
      private String userName;

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

      @Value("${jdbc.filters}")
      private  String staticFilter;

      @Value("${jdbc.maxActive}")
      private int maxActive;

      @Value("${jdbc.initialSize}")
      private int initialSize;

      @Value("${jdbc.maxWait}")
      private int maxWait;

      @Value("${jdbc.minIdle}")
      private int minIdle;

      @Value("${jdbc.timeBetweenEvictionRunsMillis}")
      private int timeBetweenEvictionRunsMillis;

      @Value("${jdbc.minEvictableIdleTimeMillis}")
      private int minEvictableIdleTimeMillis;

      @Value("${jdbc.maxOpenPreparedStatements}")
      private int maxOpenPreparedStatements;

      @Value("${jdbc.testWhileIdle}")
      private  boolean testWhileIdle;

      @Value("${jdbc.testOnBorrow}")
      private boolean testOnBorrow;

      @Value("${jdbc.testOnReturn}")
      private boolean testOnReturn;

      @Value("${jdbc.poolPreparedStatements}")
      private boolean poolPreparedStatements;

      @Value("${jdbc.asyncInit}")
      private boolean asyncInit;

      @Bean
      public DataSource druidDataSource(){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDbType("MYSQL");
            dataSource.setDriverClassName(this.driverClass);
            dataSource.setUrl(this.jdbcUrl);
            dataSource.setUsername(this.userName);
            dataSource.setPassword(this.password);
            dataSource.setMaxActive(this.maxActive);
            dataSource.setInitialSize(this.initialSize);
            dataSource.setMaxWait(this.maxWait);
            dataSource.setMinIdle(this.minIdle);
            dataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
            dataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
            dataSource.setMaxOpenPreparedStatements(this.maxOpenPreparedStatements);
            dataSource.setTestWhileIdle(this.testWhileIdle);
            dataSource.setTestOnBorrow(this.testOnBorrow);
            dataSource.setTestOnReturn(this.testOnReturn);
            dataSource.setPoolPreparedStatements(this.poolPreparedStatements);
            dataSource.setAsyncInit(this.asyncInit);
            try {
               dataSource.setFilters(this.staticFilter);
            } catch (Exception e) {
                  e.printStackTrace();
            }
            return  dataSource;
      }
      @Bean
      public  SqlSessionFactoryBean sqlSessionFactoryBean(DataSource druidDataSource) throws IOException {
           SqlSessionFactoryBean sqlSessionFactory= new SqlSessionFactoryBean();
           PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
           sqlSessionFactory.setMapperLocations(patternResolver.getResources("classpath*:mapper/*.xml"));
           sqlSessionFactory.setDataSource(druidDataSource);
           sqlSessionFactory.setTypeAliasesPackage("org.iris.api.pojo");
           return sqlSessionFactory;
      }

      @Bean(name = "transactionManager")
      public DataSourceTransactionManager dataSourceTransactionManager(DataSource druidDataSource){
           DataSourceTransactionManager manager = new DataSourceTransactionManager();
           manager.setDataSource(druidDataSource);
           return  manager;
      }

      @Bean
      public TransactionInterceptor transactionInterceptor(DataSourceTransactionManager transactionManager){
            TransactionInterceptor interceptor = new TransactionInterceptor();
            interceptor.setTransactionManager(transactionManager);
            Properties porps = new Properties();
            porps.setProperty("save*", "PROPAGATION_REQUIRED");
            porps.setProperty("del*", "PROPAGATION_REQUIRED");
            porps.setProperty("update*", "PROPAGATION_REQUIRED");
            porps.setProperty("get*", "PROPAGATION_REQUIRED,readOnly");
            porps.setProperty("find*", "PROPAGATION_REQUIRED,readOnly");
            porps.setProperty("*", "PROPAGATION_REQUIRED");
            interceptor.setTransactionAttributes(porps);
            return interceptor;
      }

}
  • druid.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/iris?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT&allowPublicKeyRetrieval=true
jdbc.user=root
jdbc.password=123456
jdbc.filters=stat
jdbc.maxActive=20
jdbc.initialSize=1
jdbc.maxWait=60000
jdbc.minIdle=1
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=true
jdbc.maxOpenPreparedStatements=20
jdbc.asyncInit=true
  • WebMvcConfig
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.iris.api.controller")
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/views/",".jsp");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("home");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值