0

I have an Interface say A, and five implementations for it say A1, A2, A3, A4, A5 in the same package. Now when starting spring application, I only want to load one say A1 out of A1, A2, A3, A4, A5 depending upon autowiring. I dont want to load others as it will make the application heavy if there are many classes like those. Please explain possible answer.

Rajdeep
  • 270
  • 2
  • 11

1 Answers1

2

@Qualifier

Assume you have following context:

<bean id="a1_beanId" class="com.A1" >
</bean>

<bean id="a2_beanId" class="com.A2" >
</bean>

You have to use qualifier to autowire A interface with correct realization. Autowiring then happens by bean id.

@Autowired
@Qualifier("a1_beanId")
private A yourA1Bean;

@Lazy

To prevent beans being loaded to spring context you have to switch on lazy mode using annotation @Lazy or lazy-init="true" for xml config.

A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • Thanks for your reply, but muy question is about stopping the loading of classes which are not getting autowired. – Rajdeep Jul 28 '16 at 06:45
  • @Rajdeep, I improved my answer – Rudziankoŭ Jul 28 '16 at 07:32
  • If we move to lazy initialization, spring still load all classes, I want to jsut stop that loading of classes. – Rajdeep Jul 29 '16 at 06:10
  • Then you have met this case: `if the lazy-initialized bean is the dependency of a singleton bean that is not lazy-initialized, when the ApplicationContext is eagerly pre-instantiating the singleton, it will have to satisfy all of the singletons dependencies, one of which will be the lazy-initialized bean! So don't be confused if the IoC container creates one of the beans that you have explicitly configured as lazy-initialized at startup` – Rudziankoŭ Jul 29 '16 at 07:04
  • Its not about bean instanciation, its about loading only selected classes when loading spring application context – Rajdeep Jul 29 '16 at 11:03
  • @Rajdeep, I asked question about this. http://stackoverflow.com/questions/38694980/spring-is-lazy-initialization-preventing-class-to-be-loaded – Rudziankoŭ Aug 01 '16 at 13:43