Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring DI - do not initialise all the dependent beans

I have a ServiceA which has a dependency on ServiceB. The serviceB comes from a spring bean file with lazy-init=true i.e, I only want serviceB to be initialised when and if I ask for that bean.

However I do use ServiceA throughout my application and when we do a setter based injection ServiceB gets initialised.

I want ServiceA to not initialise ServiceB until any method in ServiceA is called that needs ServiceB. One way of doing this was using the Aspects but I was looking at the simplest possible solution for this particularly in the Spring XML file for serviceB or some annotation in serviceB or any proxy flag.

like image 683
Kannan Ekanath Avatar asked Nov 14 '11 11:11

Kannan Ekanath


People also ask

Can we use @bean without @configuration?

@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.

Are beans in Spring eagerly initialized by default?

Overview. By default, Spring creates all singleton beans eagerly at the startup/bootstrapping of the application context. The reason behind this is simple: to avoid and detect all possible errors immediately rather than at runtime.

Can we create two beans with different ID in Spring?

If you define two beans of same class, without different bean id or qualifiers ( identifier) , Spring container will not be able to understand which bean to be loaded , if you try to access the bean by passing the classname and you will get NoUniqueBeanDefinitionException as there are two qualifying TestBean.

Can you Autowire byType when multiple beans?

autowire byType - For this type of autowiring, class type is used. So there should be only one bean configured for this type in the spring bean configuration file. autowire by constructor - This is almost similar to autowire byType, the only difference is that constructor is used to inject the dependency.


1 Answers

I think LazyInitTargetSource does what you need.

Useful when a proxy reference is needed on initialization but the actual target object should not be initialized until first use. When the target bean is defined in an ApplicationContext (or a BeanFactory that is eagerly pre-instantiating singleton beans) it must be marked as "lazy-init" too, else it will be instantiated by said ApplicationContext (or BeanFactory) on startup.

like image 136
Tomasz Nurkiewicz Avatar answered Oct 30 '22 11:10

Tomasz Nurkiewicz