pevgen
pevgen

Reputation: 151

How can I create the spring bean after all other beans?



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.

Upvotes: 0

Views: 2685

Answers (4)

Namachi
Namachi

Reputation: 33

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
}

Upvotes: 0

andrearro88
andrearro88

Reputation: 264

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
    }
}

Upvotes: 1

nasko.prasko
nasko.prasko

Reputation: 21

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

Upvotes: 0

Marcin Szymczak
Marcin Szymczak

Reputation: 11433

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" />

Upvotes: 1

Related Questions