For example, I have 3 beans in my spring configuration: A, B, C. And I want to create bean B and C as usual. And than (when all others beans were created) I want to ask spring to create bean A.
Any suggestion ?
Thanks.
Asked
Active
Viewed 1,948 times
0

pevgen
- 151
- 2
- 12
-
What you are trying to achieve? It's better to describe real problem. – StanislavL May 24 '17 at 07:16
-
What about using @DependsOn? https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/DependsOn.html http://www.concretepage.com/spring/example_dependson_spring – RubioRic May 24 '17 at 07:19
-
Similar question on SO: https://stackoverflow.com/a/22089047/1934211. You can also refer to Spring Jira that describes such a feature using depends-on: https://jira.spring.io/browse/SPR-3948 – OutOfMind May 24 '17 at 07:32
-
what is the reason you want to order them? Can you explain the problem in detail? Reason being spring takes care of the dependencies by itself. One use case to create bean A after B and C would be that you want to use B and C while bean A initialization. That is automatically taken care if you autowire B and C in bean A. So the answer will depend on what you are trying to achieve. – yaswanth May 24 '17 at 10:08
4 Answers
1
You should try @DependsOn
adnotation
For example
<bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao">
<property name="manager" ref="manager" />
</bean>
<bean id="manager" class="ManagerBean" />
<bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" />

Marcin Szymczak
- 11,199
- 5
- 55
- 63
-
Colleagues, thank you for your answers. But "dependsOn" works well for few beans. If I have a lot of beans it is not a good solution. So, I am looking for the solution for the general case. – pevgen May 24 '17 at 07:37
1
Spring framework triggers a ContextRefreshedEvent
once the contexts has been fully refreshed and all the configured beans have been created.
You could try to create a listener to catch that event and initialise bean A.
@Component
public class ContextRefreshedEventListener implements
ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// Init your bean here
}
}

andrearro88
- 254
- 3
- 9
0
I know it's not really a bean ordering answer, but maybe you can achieve your goal with a @PostConstruct
method that will be called just after a bean is constructed, dependencies are injected and all properties are set.
best nas

nasko.prasko
- 21
- 3
0
Easier way to do this would be using @Lazy
annotation to your bean. This makes your bean do not get initialized eagerly during context initialization. In simple words,your bean will get created when you ask for it, not before.
@Bean
@Lazy
public A beanA() {
//some code here
}

Namachi
- 33
- 8