具体的为什么需要这样写才可以注入service目前还没有理解透,只是多次试验后发现这样可以注入.
因为LoginInterceptor注册的时候使用的是new的方式,这个时候就需要通过构造函数的方式进行注入
//这里写法基本都一样
public class LoginInterceptor extends HandlerInterceptorAdapter {
private RoleService roleService;
private LoginConfig loginConfig;
protected Logger logger;
//唯一不同的是这里写个构造方法
public LoginInterceptor(RoleService roleService){
this.roleService =roleService;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//调用roleService方法
roleService.menght();
}
}
@Configuration
public class MyWebConfigureAdapter extends WebMvcConfigurerAdapter {
//service注入在拦截器的注册器中
@Autowired
private RoleService roleService;
@Autowired
private LoginConfig loginConfig;
@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
//registry.addInterceptor(new LoggerInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new LoginInterceptor(roleService,loginConfig)).addPathPatterns("/**");
super.addInterceptors(registry);
}
}