Home  >  Q&A  >  body text

java - spring injection is null problem

As shown in the picture:

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver{

    @Autowired
    private RedisTemplate<String,User> redisTemplate;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if(parameter.getParameterAnnotation(CurrentUser.class)!=null&& parameter.getParameterType()==User.class){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request= (HttpServletRequest) webRequest.getNativeRequest();
       // todo
        return null;
    }
}

After the created class implemented HandlerMethodArgumentResolver, it was found that the bean instances injected into it failed. The redisTemplate instance above was null when running, and other classes in the same package were normal.
May I ask what caused the bean injection to fail?

phpcn_u1582phpcn_u15822712 days ago481

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-17 09:59:40

    The situation of UserArgumentResolver对象没有被IoC容器管理, 因为在@Autowired注解没有配置required=false的情况下spring发现没有该对象会直接抛出Exception, 不会出现注入null you use.

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-17 09:59:40

    HandlerMethodArgumentResolver interface should be instantiated by spring, not managed by IOC container instantiation

    reply
    0
  • Cancelreply