Search code examples
springspring-bootannotationsjavabeans

How to declare multiple object with same class but using different properties in spring boot


I want declare multiple object using same class but different properties in Spring boot annotation

application.properties

test1.name=Ken
test2.name=Anthony

the code example

@Component
public class People {
    private String name;
    public String getName() {
        return this.name;
    }
}

@SpringBootApplication
public class Application {
    @AutoWired
    public People man1;

    @AutoWired
    public People man2;

    System.out.println(man1.getName());
    System.out.println(man2.getName());
} 

I try to add @ConfigurationProperties(prefix="test1") before declare man1

but it returned

The annotation @ConfigurationProperties is disallowed for this location

Solution

  • @ConfigurationProperties is only allow to be placed on the @Bean method in the @Configuration class or at the class level. For the former case , it will map the properties from the application.properties to the bean instance , which means you have to :

    @SpringBootApplication
    public class Application {
    
        @Bean
        @ConfigurationProperties(prefix="test1")
        public People man1() {
            return new People();
        }
    
        @Bean
        @ConfigurationProperties(prefix="test2")
        public People man2() {
            return new People();
        }
    } 
    

    And since both man1 and man2 are the same type , you have to further use @Qualifier to tell Spring which instance you actually want to inject by specifying its bean name. The bean name can be configured by @Bean("someBeanName"). If @Bean is used without configuring the bean name, the method name will be used as the bean name. (i.e. man1 and man2)

    @Autowired
    @Qualifier("man1")
    public People man1;
    
    @Autowired
    @Qualifier("man2")
    public People man2;