解决spirng无法注入redis工具类及dao层类(Springboot项目)

redis无法注入spring容器中

实例:在这里插入图片描述

下一步就报错,redisUtil为null,表示没有注入spring容器中

解决办法

1.首先查看RedisUtil是否注入添加@Component

部分:

@Component
public final class RedisUtil {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

2. 查看SecuirtyConfig类

修改后的代码

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //外面的configure是spring管理的  @Autowired注入就可以了
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    JobUserMapper jobUserMapper;
    @Bean
    UserDetailsService customUserService(){ //注册UserDetailsService 的bean
        return new UserDetailsServiceImpl();
    }



    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
    /*
    * 重写这个方法
    * 作用:访问所以接口不走过滤器,直接返回数据结果
    * */
    //@Override
    //public void configure(WebSecurity web) {
    //    web.ignoring().antMatchers("/**");
    //}

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/static/**","/index.html","/favicon.ico","/avatar.jpg").permitAll()
                .antMatchers("/api/callback","/api/processCallback","/api/registry","/api/registryRemove").permitAll()
                .antMatchers("/doc.html","/swagger-resources/**","/webjars/**","/*/api-docs").anonymous()
                .anyRequest().authenticated()
                .and()
                 //因为这里filter是你 new出来的  所以一面的@autowired不生效的 只能从构造参数传进去
                .addFilter(new JWTAuthenticationFilter(authenticationManager(),redisUtil,jobUserMapper))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

因为这里configure是spring管理的 注入就可以了
重点两个地方:
在这里插入图片描述
在这里插入图片描述

3.JWTAuthenticationFilter类(重点:这个是new出来的)

修改后的代码:

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    //构造方法中参数
    private final RedisUtil redisUtil; 
    private final JobUserMapper jobUserMapper;
    private final ThreadLocal<Integer> rememberMe = new ThreadLocal<>();
    private final AuthenticationManager authenticationManager;
    
    //构造方法
    public JWTAuthenticationFilter(AuthenticationManager authenticationManager, RedisUtil redisUtil,
                                   JobUserMapper jobUserMapper) {
        this.authenticationManager = authenticationManager;
        this.redisUtil = redisUtil;
        this.jobUserMapper = jobUserMapper;
        super.setFilterProcessesUrl("/api/auth/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        // 从输入流中获取到登录的信息
        try {
            LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
            //Object o = redisUtil.get(loginUser.getToken());
            redisUtil.set("zhangsan", "asdasd");
            System.out.println(redisUtil.get("zhangsan").toString());

因为是 new JWTAuthenticationFilter(authenticationManager(),redisUtil,jobUserMapper),所以一面的@autowired不生效的 只能从构造参数传进去,外面的configure是spring管理的 @autowired注入就可以了

解决了,这样我们的类或者工具类就可以获取值了

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值