Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: define and wire a bean in the same class

Tags:

spring

By using Java Config, how can I wire a bean in the same class when it is defined?

For example:

@Bean
public Foo foo() {
    return new Foo();
}

@Autowired
private Foo foo;

@Bean
public Bar bar() {
    return new Bar(foo);
}

Note: this code returns an error.

like image 759
vdenotaris Avatar asked Apr 22 '14 08:04

vdenotaris


People also ask

Can we use @component and @bean in same class?

No. It is used to explicitly declare a single bean, rather than letting Spring do it automatically. If any class is annotated with @Component it will be automatically detect by using classpath scan. We should use @bean, if you want specific implementation based on dynamic condition.

Does Spring allow multiple bean definitions of same class?

This is the simplest and easiest way to create multiple beans of the same class using annotations. In this approach, we'll use a Java-based configuration class to configure multiple beans of the same class.

How do you make two beans of the same class in Spring?

The default autowiring is by type, not by name, so when there is more than one bean of the same type, you have to use the @Qualifier annotation.

Can I have 2 bean definition of a class with Singleton scope?

It will throw an error at runtime, as you can not define two Sspring beans of the same class with Singleton Scope in XML.


1 Answers

@Bean
public Foo foo() {
    return new Foo();
}


@Bean
public Bar bar() {
    return new Bar(foo());
}

Alternatively the Bar bean could also be configured as so:

@Bean
public Bar bar(Foo foo) {
    return new Bar(foo);
}
like image 118
geoand Avatar answered Oct 05 '22 19:10

geoand