Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a bean into custom argument resolver?

Hello i use spring boot 1.3.2 version. I have a custom argument resolver which's name is ActiveCustomerArgumentResolver. Everything is great, resolveArgument method works fine but i can't initialize my service component which is of my custom arg. resolver. Is there a problem with lifecycle process? Here is my code:

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");
    }
}

}

like image 327
C.Köse Avatar asked Oct 31 '25 09:10

C.Köse


1 Answers

Let the Spring create the resolver for you by making it a Component:

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

Then inject the resolver into your WebConfig instead of simply using the new, like following:

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

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(activeCustomerArgumentResolver);
    }
}
like image 106
Ali Dehghani Avatar answered Nov 02 '25 23:11

Ali Dehghani