springboot 2.0 改动 相关代码

一.启动类

package com.basewin.tms;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//注意:
/*
在springboot1.0中用的是
import org.springframework.boot.web.support.SpringBootServletInitializer;
*/
//2.0中用的是这个
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@ComponentScan(basePackages = {"com.basewin.tms"})
@EnableTransactionManagement //如果mybatis中service实现类中加入事务注解,需要此处添加该注解
@MapperScan("com.basewin.tms.dao")//扫描dao层
public class TmsApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(TmsApplication.class, args);
    }
}

另外 springboot2.0 在tomcat7 中运行会报错, java.lang.NoClassDefFoundError: javax/el/ELManager

解决办法:下载javax-el-api3.0.0.jar,放到jdk或者只放tomcat/lib都可(直接使用tomcat8也可解决)

<dependency>
       <groupId>javax.el</groupId>
       <artifactId>javax.el-api</artifactId>
       <version>3.0.0</version>
       <scope>provided</scope>
   </dependency>

二.log4j

springboot2.0已经没有了 log4j ,建议使用 slf4j ,代码如下

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//将你要加入日志的类加进去
protected static Logger logger = LoggerFactory.getLogger(RemotecontrolController.class);

三,拦截器

springboot1.0 采用的是继承WebMvcConfigurerAdapter

@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    //关键,将拦截器作为bean写入配置中
    @Bean
    public AuthInterceptor myAuthInterceptor() {
        return new AuthInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器
        InterceptorRegistration ir = registry.addInterceptor(myAuthInterceptor());
        // 配置不拦截的路径
        ir.excludePathPatterns("/RemotecontrolController/*");
        // 配置拦截的路径
        ir.addPathPatterns("/**");
        // 还可以在这里注册其它的拦截器
        //registry.addInterceptor(roleInterceptor).addPathPatterns("/getstudent");
        //registry.addInterceptor(new OtherInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        //第一个参数解析器
        argumentResolvers.add(oenCurrentMethodArgumentResolver());
        //第二个参数解析器
        argumentResolvers.add(twoCurrentUserMethodArgumentResolver());
        super.addArgumentResolvers(argumentResolvers);
    }

    @Bean//第一个参数解析器
    public OenCurrentMethodArgumentResolver oenCurrentMethodArgumentResolver() {
        return new OenCurrentMethodArgumentResolver();
    }

    @Bean//第二个参数解析器
    public TwoCurrentMethodArgumentResolver twoCurrentUserMethodArgumentResolver() {
        return new TwoCurrentMethodArgumentResolver();
    }
}

 在2.0中 推荐使用  接口 WebMvcConfigurer,具体代码如下

package com.basewin.tms.servlet.Intercept;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;

/**
 * 注册拦截器和参数解析器在 WebMvcConfigurerAdapter 中,需要注意,装配拦截器@Autowired
 *
 *springboot2.0  继承WebMvcConfigurerAdapter已经过时改用 implements WebMvcConfigurer 接口
 *
 */
@Configuration
public class MyWebMvcConfigurerAdapter implements  WebMvcConfigurer {
    //关键,将拦截器装配
    @Autowired
    private AuthInterceptor myAuthInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器
     /*   InterceptorRegistration ir = registry.addInterceptor(myAuthInterceptor());
        // 配置不拦截的路径
        ir.excludePathPatterns("/RemotecontrolController/*");
        // 配置拦截的路径
        ir.addPathPatterns("/**");*/
        registry.addInterceptor(myAuthInterceptor).addPathPatterns("/**").excludePathPatterns("/RemotecontrolController/**","/static/**");
        // 还可以在这里注册其它的拦截器
        // registry.addInterceptor(new OtherInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        //第一个参数解析器
        argumentResolvers.add(oenCurrentMethodArgumentResolver());
        //第二个参数解析器
        argumentResolvers.add(twoCurrentUserMethodArgumentResolver());
    }

    @Bean//第一个参数解析器
    public OenCurrentMethodArgumentResolver oenCurrentMethodArgumentResolver() {
        return new OenCurrentMethodArgumentResolver();
    }

    @Bean//第二个参数解析器
    public TwoCurrentMethodArgumentResolver twoCurrentUserMethodArgumentResolver() {
        return new TwoCurrentMethodArgumentResolver();
    }

}

四,Redis缓存配置 

2.0默认引入了Lettuce, 替代了之前的jedis作为底层的redis链接方式, 同样Lettuce底层基于netty框架,使用异步的方式,访问redis,并且如果结合之前的Webflux, 可以达成请求的全异步, 同样对比于之前的jedis,统一了redis和redis-cluster的访问方式,简化了开发人员的使用方式,同时也提高了redis的访问速度。

pom.xml

<!--redis包开始-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--spring2.0集成redis所需common-pool2-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
<!--redis包结束-->

application.properties

# Redis数据库索引(默认为0)
#spring.redis.database=0
# Redis服务器地址
spring.redis.host=*****
spring.redis.port=6379
spring.redis.password=*****
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
package com.basewin.tms.servlet.redis;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
import org.springframework.cache.interceptor.KeyGenerator;
import java.lang.reflect.Method;
/**
 * Redis缓存配置类2.0
 * niuhao 2018-07-09
 */
@Configuration
@EnableCaching //开启缓存支持
public class RedisCacheAutoConfiguration extends CachingConfigurerSupport {

    /**
     * RedisTemplate配置
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setValueSerializer(valueSerializer());
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(keySerializer());
        template.afterPropertiesSet();
        return template;
    }

    //缓存管理器

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(
                        valueSerializer()))
                .disableCachingNullValues();

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)

                .cacheDefaults(config)
                .transactionAware()
                .build();

        return redisCacheManager;
    }

    /**
     * 缓存对象集合中,缓存是以 key-value 形式保存的。当不指定缓存的 key 时,SpringBoot 会使用 SimpleKeyGenerator 生成 key。
     *
     * @return
     */
    @Bean
    public KeyGenerator KeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

}

猜你喜欢

转载自blog.csdn.net/qq_39526250/article/details/81318333