Model这个对象是怎么自动注入到容器里面的?

在web工程中很多的实例是自动注入到容器中的,不用我们人为的创建。比如model等等。今天我以自己新建的一个MiaoshaUser为例,实现自动注入到容器中。

 

先添加一个webConfig继承 WebMvcConfigurerAdapter

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{

    @Autowired
    private UserArgumentResolvers userArgumentResolvers;

    @Override
    public void addArgumentResolvers(List argumentResolvers) {
        argumentResolvers.add(userArgumentResolvers);
    }
}

 

再来写进自己想注入的类 UserArgumentResolvers

@Service
public class UserArgumentResolvers implements HandlerMethodArgumentResolver {

    @Autowired
    private MiaoshaUserService miaoshaUserService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class parameterType = parameter.getParameterType();
        return parameterType == MiaoshaUser.class;//遍历是否是需要的类型
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

        String cookieToken = request.getParameter(MiaoshaUserService.COOKIE_NAME_TOKEN);
        String paramToken = getCookieValue(request,MiaoshaUserService.COOKIE_NAME_TOKEN);

        if (StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)){
            return null;
        }
        String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
        return miaoshaUserService.getMiaoshaUserByToken(response,token);
    }

    public String getCookieValue(HttpServletRequest request,String cookieName){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)){
                return cookie.getValue();
            }
        }
        return null;
    }
}

 

你可能感兴趣的:(Model这个对象是怎么自动注入到容器里面的?)