简体   繁体   中英

Apply @ConfigurationProperties to each element in a list

I'm trying to build an application level round robin mechanism to rotate between data sources in a Spring Application.

For a single datasource, I can have a bean

@ConfigurationProperties(prefix = "spring.datasource")
public DataSource ...

which works fine.

Is it possible to have something like

@ConfigurationProperties(prefix = "spring.datasource")
public List<DataSource> ...

where the config properties from the file are applied to each object in the list? I to keep it a list since the number of data sources may change in time and may come from a config, say from dynamo DB. (Of course changes will only be reflected on application restart, but it avoids needing code changes)

Im not sure that solution will resolve your problems.

U can define the java class as below:

@ConfigurationProperties(prefix = "spring")
public class DataSources {

    private List<DataSource> datasource;

    public static class DataSource {
        private String name;
        private String url;
    }
}

That will map the below configuration

spring:
    datasource[0]:
        name: mysql
    datasource[1]:
        name: mongo
    datasource[2]:
        name: mssql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM