Luisao
Luisao

Reputation: 505

I want to set a HashMap with SpringBoot and get the values next in other class

I'm working with Spring Boot, and I need to load a HashMap with some values from Class A.

Then, I need to get the values from this HashMap in Class B, Class C, etc.

So I need a HashMap that load at first my values, and then, use this Map throughout the other classes.

Thanks.

Upvotes: 3

Views: 25645

Answers (2)

MyTwoCents
MyTwoCents

Reputation: 7624

Now values which you are trying to load can be static or dynamic (from DB)

For static data

@Configuration
public class MyConfig {

   @Bean 
   public Map<String, String> myVal(){
      Map<String, String> map = new HashMap<String, String>();
      map.put("Sample", "Value");
      return map;      
   }


}

And you can Autowire then in Other Component classes as suggested by @Gro

@Autowired
private Map<String, String> myVal;

For Dynamic Data

With XML

<bean class="com.example.DbConfigLoader" init-method="initMethod">

With Annotation

@Configuration
public class MyConfig {

  @Bean(initMethod="initMethod")
  public DbConfigLoader dbConfigLoader() {
    return new DbConfigLoader();
  }

}



public class DbConfigLoader {

    @Autowired
    private DbConfigRepository repository;

    private DbConfig dbConfig;

    @PostConstruct   // Optional if you don't want to add initMethod in Bean Definition
    public void initMethod(){

    // Logic for your dynamic Data load
        dbConfig = repository.findOne(1L);  
    }

    public DbConfig getDbConfig() {
        return dbConfig;
    }
}

Your bean is ready to be used in Any other classes.

Upvotes: 4

Gro
Gro

Reputation: 1683

I assume you have a Configuration class that creates and returns Spring Beans.

import org.springframework.context.annotation.*;

@Configuration
public class MyConfiguration {

   /* Feel free to change the type of key and value in the Map 
    * from String, String to anything of your choice 
    */
   @Bean 
   public Map<String, String> myMap(){
      java.util.Map<String, String> map = new java.util.HashMap<String, String>();
      map.put("Hello", "world");
      return map;      
   }

  /*Your other bean exporting methods*/

}

Once done, you are able to inject this map to any Spring Component or Service like so

@Component
public class Foo {

    @Autowired
    private Map<String, String> myMap;

    /* You can even put the annotation on a setter */

}

Upvotes: 5

Related Questions