user1491636
user1491636

Reputation: 2446

Spring Boot - bean definition

I'm looking into using Spring Boot for a new application but I'm having trouble figuring out the best approach to create the application beans.

At a high-level, this would be a web application that can have one or more beans of the same type - each with different property values. If I need to add a new bean of the same type, I should only have to configure it. Typically, if I was using Spring MVC, I would just define each bean in application context and load in the property values via a context file. Spring Boot prefers to do away with xml config, but I'm not sure how to translate the bean definitions into a Spring Boot solution. How do I still take advantage of IoC using Spring Boot.

Upvotes: 1

Views: 6852

Answers (2)

Whesley Barnard
Whesley Barnard

Reputation: 309

with Maciej Walkowiak's answer, it is also recomended to write it like this:

@Configuration
class MyConfiguration {

    @Bean
    @Qualifier("first")
    MyClass first() {
        return new MyClass();
    }

    @Bean
    @Qualifier("second")
    MyClass second() {
        return new MyClass();
    }
}

then later when you autowire you can use:

@Autowired 
@Qualifier("second")
private MyClass myClass;

Upvotes: 3

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

Actually this has nothing to do with Spring Boot. As you mentioned, it supports both Java and XML bean configurations.

You can easily create multiple beans out of the same class using Java configuration.

XML config like:

<bean id="first" class="com.foo.MyClass" />

<bean id="second" class="com.foo.MyClass" />

translates into:

@Configuration
class MyConfiguration {

    @Bean
    MyClass first() {
        return new MyClass();
    }

    @Bean
    MyClass second() {
        return new MyClass();
    }
}

Upvotes: 3

Related Questions