介绍一下springboot的一些自定义配置。自定义配置前,需要加入一些依赖,在学习笔记1中都要介绍
首先自己一个拦截器:
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("interceptor is working now----");
return true;
}
。。。。。省略其它
}
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加自定义拦截器,设置路径
registry.addInterceptor(new CustomizeInterceptor()).addPathPatterns("/test/**");
super.addInterceptors(registry);
}
}
在使用redis 保存key会产生 \xac\xed\x00\x05t\x00这样的乱码,这是因为springboot中默认redistemplate使用的序列化key类不是StringRedisSerializer(),需要我们自己配置一下:
public static RedisTemplate redisTemplate;
@Autowired public RedisConfigurer(RedisTemplate redisTemplate) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
this.redisTemplate = redisTemplate;
}
对于有的web项目,需要用户登录才能授权访问,可以通过以下配置实现用户登录授权:
@EnableWebSecurity public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override protected void configure(HttpSecurity http) throws Exception {
//指定路径需要登录权限,对静态资源放行,无需授权即可访问
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/images/**",
//请求路径包含order的,都需要去登陆
"/login").permitAll().antMatchers("/order/**").hasRole(("USER")).and().
formLogin();//在该处追加.loginPage("/tologin");
http.csrf().disable();
//单点登录。如果已经登录,其它登录会使当前登录session失效。进一步操作则需要再次登录
http.sessionManagement().maximumSessions(1).expiredUrl("/login");
// BCryptPasswordEncoder 加密类
//如果登出,使session无效
http.logout().invalidateHttpSession(true);
}
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()//全局默认用户
.withUser("admin").password("admin").roles("USER");
}
springboot 提供一个工具类可以加载application.yml中的配置文件,如果要读取application.yml 以下参数:
spring:
username: user
password: pass
role:
- admin
- guest
@Component
@ConfigurationProperties(prefix = "spring")
public class PropertiesConfigurer {
private String username;
private String password;
private List role=new ArrayList<>();
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public List getRole() {
return role;
}
}
@Autowired private PropertiesConfigurer propertiesConfigurer;
public void () {
....省略
String name= propertiesConfigurer.getUsername();
}
使用@value注解直接获取:
private @Value("${spring.username.user: }") String user;