Trying to use JSR330ScopeMetadataResolver with Spring boot without success

232 views Asked by At

I am trying to retrofit Spring DI into an existing application using Spring Boot. I want to use JSR-330 annotations instead of Spring's. I would like to make prototype scope the default so I don't have to use non-JSR-330 scope @Scope("prototype") everywhere. I first tried to install the JSR330ScopeMetadataResolver using:

  SpringApplication application = new SpringApplication(OurApplication.class);
  ConfigurableApplicationContext context = application.createContext();
  context..setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());
  application.run(args);

I still get a singleton when injecting a class with no annotation. I then tried using an ApplicationContextInitializer to do the same thing. Either way, I get a singleton injected. In the debugger, I verified with the initializer that Jsr330ScopeMetadataResolver is getting set in the ApplicationContext. In the Jsr330ScopeMetadataResolver instance, I see a map is getting populated in the default constructor with key /value as singleton. I obviously are missing something. Does anyone know what that is?

1

There are 1 answers

0
Jim McMaster On

We finally were able to figure this out. The solution was:

  private static final String CONTEXT_PACKAGES_TO_SCAN = 
      "my.company.package.*";


  public static void main(String[] args) {
      SpringApplication application = new SpringApplication(
          MainApplication.class);
      application.addInitializers(new Jsr330Initializer());
      application.run(args);
  }


  public static class Jsr330Initializer implements 
      ApplicationContextInitializer<AnnotationConfigApplicationContext> 
  {

      @Override
      public void initialize(AnnotationConfigApplicationContext context) {
          context.setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());
          context.scan(CONTEXT_PACKAGES_TO_SCAN);
      }
}

The key is to perform context.scan() in the initializer. Packages to scan must end in ".*", or the main application gets added twice and Spring fails to start.