简体   繁体   中英

Collection data in Spring Java based configuration

I am working on migrating Spring XML configuration to Java based configuration. During the process, I run into a situation of collection type data and don't know how to handle it in the Java based configuration. For example,

<util:map id="imageDimensions" map-class="java.util.HashMap">
    <entry key="regular" value="640x480" />
    <entry key="small" value="320x240" />
    <entry key="thumb" value="200x150" />
</util:map>

If I don't want to have this map data in Java configuration, what I need to do about it?

You have to add bean in your configuration:

@Bean
public Map<String, String> imageDimensions() {
  // create your map
}

If you prefer to have your map data in for example properties file you have to inject Environment field and then by invoking getProperty() retrieve and set all needed elements.

 @Configuration
 public class AppConfig {

     @Inject Environment env;

     @Bean
     public Map<String, String> imageDimensions() {
        Map<String, String> map = new HashMap<>();
        // create your map
        return map;
     }

 }

You can also of course read this data from xml or yaml file

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