如何将bean注入自定义参数解析器?

时间:2016-02-10 11:26:16

标签: dependency-injection spring-boot autowired

您好我使用spring boot 1.3.2版本。我有一个自定义参数解析器,其名称为ActiveCustomerArgumentResolver。一切都很棒,resolveArgument方法工作正常但我无法初始化我的自定义arg服务组件。解析器。生命周期过程有问题吗?这是我的代码:

import org.springframework.beans.factory.annotation.Autowired;
//other import statements

public class ActiveCustomerArgumentResolver implements HandlerMethodArgumentResolver {

@Autowired
private CustomerService customerService;

@Override
public boolean supportsParameter(MethodParameter parameter) {
    if (parameter.hasParameterAnnotation(ActiveCustomer.class) && parameter.getParameterType().equals(Customer.class))
        return true;
    else
        return false;
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    Principal userPrincipal = webRequest.getUserPrincipal();
    if (userPrincipal != null) {
        Long customerId = Long.parseLong(userPrincipal.getName()); 
        return customerService.getCustomerById(customerId).orNull(); //customerService is still NULL here, it keeps me getting NullPointerEx.
    } else {
        throw new IllegalArgumentException("No user principal is associated with the current request, yet parameter is annotated with @ActiveUser");
    }
}

}

2 个答案:

答案 0 :(得分:4)

让Spring为你创建解析器,方法是Component

@Component
public class ActiveCustomerArgumentResolver implements HandlerMethodArgumentResolver {...}

然后将解析器注入WebConfig,而不是简单地使用new,如下所示:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Autowired private ActiveCustomerArgumentResolver activeCustomerArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(activeCustomerArgumentResolver);
    }
}

答案 1 :(得分:0)

这就是我解决问题的方法,而不是一般问题,但对我有很大的帮助:

Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends WebMvcConfigurerAdapter {

private static final Logger logger = LoggerFactory.getLogger(Application.class);

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
    argumentResolvers.add(activeCustomerArgumentResolver());
}

@Bean
public ActiveCustomerArgumentResolver activeCustomerArgumentResolver() {
    return new ActiveCustomerArgumentResolver();
}