拦截器中 Springboot @Autowired 组件的 NullPointerException

Nat*_*an 1 java spring redis jedis spring-boot

我有一个组件,其主要工作是返回 Jedis 实例,它如下所示:

@Component
public class JedisConfig {

    private Jedis jedis;

    public JedisConfig() {
        jedis = new Jedis("localhost", 6379);
    }

    public Jedis getJedis() {return jedis;}
}
Run Code Online (Sandbox Code Playgroud)

然后,我使用 Jedis 实例在拦截器的 preHandler 中执行一些操作:

public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisConfig jc;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Jedis jedis = jc.getJedis();
        
        // do some other stuff with jedis below
    }
}

Run Code Online (Sandbox Code Playgroud)

但我在调用时收到 NullPointerException jc.getJedis(),但我不明白为什么会发生这种情况。

在相关说明中,我在单元测试中做了几乎完全相同的事情,并且运行良好:

@Autowired
private JedisConfig jc;

@Test
public void testJedis(){
    Jedis jedis = jc.getJedis();

    jedis.set("user", "role");
    assertThat(jedis.get("user"),is("role"));
}
Run Code Online (Sandbox Code Playgroud)

以下是我将拦截器添加到注册表的方法:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor())
                .addPathPatterns("/user/roleChange");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有人知道如何解决此问题,请告诉我。太感谢了!

Nik*_*las 5

不是AuthInterceptorSpring bean,并且JedisConfig不是自动装配的且为 null。只要在@Configuration类中使用拦截器,就可以在那里进行自动装配并封装JedisConfig拦截器。

@RequiredArgsConstructor // either use Lombok or write the constructor by yourself
public class AuthInterceptor implements HandlerInterceptor {

    private final JedisConfig jc;
}
Run Code Online (Sandbox Code Playgroud)
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JedisConfig jc;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor(jc))
                .addPathPatterns("/user/roleChange");
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以将 视为AuthInterceptor组件并在WebConfig类中自动装配它:

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisConfig jc;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Jedis jedis = jc.getJedis();
        
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowire
    private AuthInterceptor authInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/user/roleChange");
    }
}
Run Code Online (Sandbox Code Playgroud)