简体   繁体   中英

Jersey Test + Spring - not injecting beans into Controllers

Could someone tell me please how to get spring injection working on Controller classes registered in resource config:

ResourceConfig resourceConfig = new ResourceConfig(controllerClasses);

I include the spring context like this:

    private void mergeSpringContext(ResourceConfig resourceConfig) {
        ContextConfiguration annotation = getClass().getAnnotation(ContextConfiguration.class);
        if(annotation != null) {
            Class<?>[] contextClasses = annotation.classes();
//            ApplicationContext context = new AnnotationConfigApplicationContext(contextClasses);
//            resourceConfig.property("contextConfig", context);
            resourceConfig.registerClasses(contextClasses);
        }
    }

You can see two approaches there but neither works. Jersey-test always creates a new instance of the controller and spring can't know about it. Is there a way to make jersey use spring-instantiated controller (which is managed and will have all fields set) bean? Or do I have to get myself into trouble of using some AOP (@Configurable on the controller class).

There is something called

jersey-spring3

and it's supposed to do it. And I think it does but not in the way I'd like it to - it searches for applicationContext.xml on my classpath. And this is not what I want because it is the test case which specifies which spring contexts to load.

Thanks!

// EDIT

I managed to use spring-instantiated controllers in my application like this:

    private void mergeSpringContext(ResourceConfig resourceConfig) {
        ContextConfiguration annotation = getClass().getAnnotation(ContextConfiguration.class);
        if(annotation != null) {
            Class<?>[] contextClasses = annotation.classes();
            ApplicationContext context = new AnnotationConfigApplicationContext(contextClasses);
            Map<String, Object> beansOfType = context.getBeansWithAnnotation(Controller.class);
            Collection<Object> controllers = beansOfType.values();
            resourceConfig.registerInstances(controllers.toArray());
        }
    }

The problem with it is that I still don't have a clue how to put spring security in there...

We do a little differently.

In our WebAppInit, we have:

ResourceConfig resourceConfig = new ResourceConfig()
  .packages(
  'foo.package1',
  'foo.package2'
)

Then a RootConfig

@Configuration
@EnableCaching
@ComponentScan(basePackages = [

Then each injectable is annotated with @Named and each usage with @Inject

Good luck

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