Reputation: 609
I'm using RESTEasy 3
and Spring 4
and I'm trying to inject @Autowired
an service bean into my interceptor as follow below:
But running this code it's returning Null Pointer Exception
when access my access service:
@Provider
@MyAnnotationToIntercept
public class MyInterceptor implements ContainerRequestFilter {
private MyAccessService accessService;
@Autowired
public MyInterceptor(MyAccessService accessService) {
this.accessService = accessService;
}
public MyInterceptor() {
}
@Override
public void filter(ContainerRequestContext requestContext) {
// DO SOME STUFF Using accessService
}
}
@Component
public class MyAccessService {
private MyDep1 dep1;
@Autowired
public MyAccessService(Mydep1 dep1) {
this.dep1= dep1;
}
}
Is there any way to achieve this? It's really possible?
Upvotes: 0
Views: 990
Reputation: 2327
Looks like you have placed @Autowired annotation at the wrong place. It should be above the declaration of accessService. And depending on how you have configured application context, you may/may not need a setter method for accessService instance variable.
Upvotes: 0
Reputation: 4084
You will need to use WebApplicationContextUtils
's method to get a bean inside filter which is not managed by spring. Here is the example
MyAccessService myAccessService = (MyAccessService) WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest .getServletContext()).getBean(MyAccessService.class);
And to get HttpServletRequest
instance you can use @context
injection
@Context
private HttpServletRequest httpServletRequest ;
Upvotes: 2