Using `@ConfigurationProperties` annotation on `@Bean` Method

前端 未结 4 1766
栀梦
栀梦 2020-12-14 16:38

Could someone give a MWE of how to use the @ConfigurationProperties annotation directly on a @Bean method?

I have seen countless examples o

4条回答
  •  Happy的楠姐
    2020-12-14 17:07

    You can use @ConfigurationProperties as below

    Entity Model

    public class MY_ENTITY {
        private String prop1;
        private String prop2;
        // setter & getter & toString()
    }
    

    Bean Method

    @Configuration
    public class MyClass {
    
        @Bean
        @ConfigurationProperties(prefix = "my.entity")
        public MY_ENTITY getContract() {
            return new MY_ENTITY()
                    .setProp1("prop1111111")
                    .setProp2("prop2222222")
                    ;
        }
    
        @Bean(name = "contract2")
        @ConfigurationProperties(prefix = "my.entity2")
        public MY_ENTITY getContract2() {
            return new MY_ENTITY()
                    .setProp1("prop1111.2222")
                    .setProp2("prop2222.222")
                    ;
        }
    }
    

    application.properties

    my.entity.prop1=2120180023
    my.entity.prop2=CUSTOMER_NAME111
    
    my.entity2.prop1=9994494949
    my.entity2.prop2=CUSTOMER_NAME222
    

    SpringBootApplication

    @SpringBootApplication
    public class DemoApplication implements CommandLineRunner {
    
        @Autowired
        @Qualifier("contract2")
        private MY_ENTITY myEntity;
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println(myEntity);
        }
    }
    

提交回复
热议问题