SpringBoot常用依赖


        <!--jquery-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.0</version>
        </dependency>

        <!--rabbitMQ-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- jwt-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!-- shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.6.0</version>
        </dependency>

        <!--shiro和thymeleaf整合-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--Mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!--druid数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>

        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency> 

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--springBoot-web相关依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--junit测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

常用配置类

RedisConfig

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //  om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

druidConfig

@Configuration
public class DruidConfig {
    //加载application.yaml中的Druid配置
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","root");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.1.11");  //自己的ip

        bean.setInitParameters(initParams);
        return bean;
    }

    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

shiroConfig

@Configuration
public class ShiroConfig {

    //创建 ShiroFilfter对象
    // 负责拦截所有的请求
    // 使用安全管理器来认证和授权
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 添加自定义jwt过滤器,用来验证token
        Map<String, Filter> filterMap = shiroFilterFactoryBean.getFilters();
        filterMap.put("JWTToken",new JWTFilter());  
        shiroFilterFactoryBean.setFilters(filterMap);

        //配置系统受限的资源
        //配置系统的公共资源
        Map<String,String> map = new HashMap<>();
        //拦截所有请求
        map.put("/**","JWTToken");
        map.put("/user/**","anon");  //开放/user下所有的请求
        map.put("/druid/**","anon");  //开放/druid请求
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //设置拦截后返回的页面
        shiroFilterFactoryBean.setLoginUrl("/user/login");

        return shiroFilterFactoryBean;
    }

    //创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    //创建自定义Realm
    @Bean
    public Realm getRealm(){
        // 自己定义的Realm
        CustomRealm customRealm = new CustomRealm();
        // 修改加密的凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置md5加密
        credentialsMatcher.setHashAlgorithmName("md5");
        // 设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customRealm.setCredentialsMatcher(credentialsMatcher);

        //开启缓存管理
        customRealm.setCacheManager(new RedisCacheManger());
        customRealm.setCachingEnabled(true);   //开启全局缓存
        customRealm.setAuthenticationCachingEnabled(true);  //开启认证缓存
        customRealm.setAuthenticationCacheName("authCCache");
        customRealm.setAuthorizationCachingEnabled(true);   //开启授权缓存
        customRealm.setAuthorizationCacheName("authZCache");

        return customRealm;
    }

    // thymeleaf 中shiro标签的 方言处理器
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}

常用工具类

ApplicationContext工具类 ==> 用来获取bean

@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    //获取bean
    public static Object getBean(String name){
        return context.getBean(name);
    }
}

jwt工具类

public class JWTUtil {

    // 自定义私钥
    private static final String TOKEN_SECRET = "^JDF654e2#^%&HDRe";

    //过期时间设置(30分钟)
    private static final long EXPIRE_TIME = 30*60*1000;

    // 自定义加密
    private static final Algorithm ALGORITHM =Algorithm.HMAC256(TOKEN_SECRET);

    // 获取token
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();

        // 过期时间和加密方法
        Date date=new Date(System.currentTimeMillis()+EXPIRE_TIME);

        // 数据填充
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        return builder.withExpiresAt(date).sign(ALGORITHM);
    }

    // 认证,出现错误会报异常
    public static DecodedJWT verifier(String token){
        DecodedJWT verify = JWT.require(ALGORITHM).build().verify(token);
        return verify;
    }
}

常用yml

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/%数据库名%?characterEncoding=UTF-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5 # 初始连接数
    minIdle: 10 # 最小连接池数量
    # 最大连接池数量
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    # 配置一个连接在池中最大生存的时间,单位是毫秒
    maxEvictableIdleTimeMillis: 900000
    # 配置检测连接是否有效
    validationQuery: SELECT 1 FROM DUAL
    #申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
    testWhileIdle: true
    #配置从连接池获取连接时,是否检查连接有效性,true每次都检查;false不检查。做了这个配置会降低性能。
    testOnBorrow: false
    #配置向连接池归还连接时,是否检查连接有效性,true每次都检查;false不检查。做了这个配置会降低性能。
    testOnReturn: false
    #打开PsCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    #合并多个DruidDatasource的监控数据
    useGlobalDataSourceStat: true
    #通过connectProperties属性来打开mergesql功能罗慢sQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500;

  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

  #redis
  redis:
    database: 0
    host: localhost
    port: 6379
    password:
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 500

  #热部署--静态资源立即生效
  thymeleaf:
    cache: false                    #是否开启模板缓存,默认true
    encoding: UTF-8                 #指定模板的编码,默认为: UTF-8
    mode: HTML                      #指定模板的模式,具体查看StandardTemplateModeHandlers,默认为: HTML5
    prefix: classpath:/templates/   #前缀
    suffix: .html                   #后缀
    check-template-location: true  #是否检查模板路径是否存在,默认true
    servlet:
      content-type: text/html        #响应类型,指定Content-Type,默认为: text/html
  #热部署生效
  devtools:
    restart:
      enabled: true

  #rabbitMQ
  rabbitmq:
    host: localhost
    port: 5672
    username: 123
    password: 123
    virtual-host: demo1


mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.example.demo.entity
  configuration:
    map-underscore-to-camel-case: true

mapper.xml的头和thymeleaf的依赖

<!--mapper-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--thymeleaf-->
<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org"
	  xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
posted @ 2021-09-16 14:06  一只小白的进修路  阅读(1392)  评论(0)    收藏  举报