简体   繁体   中英

How to inject spring bean into ContainerRequestFilter using AutoWired?

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?

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 ;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM