The solution to the inability to inject beans in SpringBoot

Injecting Bean in Intecepter is a null pointer exception

Java Config configuration file

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleInterceptor());
    }

}

Intercepter implementation

public class LocaleInterceptor extends HandlerInterceptorAdaptor {

    @Autowired
    ISomeService someService;

    ...
}

In this case, an error will be reported, our someService is null

Solution

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private  LocaleInterceptor localeInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeInterceptor);
    }

}

We now inject an interceptor into the configuration file, and then we can do it, no null pointer exception will be reported.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324959129&siteId=291194637