Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3 bean instantiation sequence

Tags:

java

spring

Is there anyway to specify order in which beans to be instantiated? i.e. I want specific beans to be instantiated before other beans, its like startup sequence.

I am using Spring 3.2 and annotation based declaration method.

like image 714
gpa Avatar asked Dec 07 '12 20:12

gpa


People also ask

How are beans instantiated in Spring?

Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.

Is @bean and @component same?

@Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose. @Component is compatible with Spring's auto-detection, but @Bean requires manual class instantiation.


1 Answers

If bean A depends on bean B by defining <property/>, @Autowired or <constructor-arg/> then the order is forced and fixed by the Spring container. No problem here.

But if you want to enforce specific order of bean creation which is not expressed via explicit dependencies feel free to use:

<bean id="A" depends-on="B"/> <bean id="B"/> 

or better (with annotations, works also with @Bean Java configuration):

@Service @DependsOn("B") public class A {} 

or even better... don't use it. These constructs are a code smell and often suggest you have some nasty invisible dependency between your components.

like image 129
Tomasz Nurkiewicz Avatar answered Oct 14 '22 22:10

Tomasz Nurkiewicz