Java 我想用SpringBoot设置一个HashMap,然后在其他类中获取下一个值
我正在使用SpringBoot,需要加载一个HashMap,其中包含一些来自类a的值 然后,我需要从类B、类C等的HashMap中获取值 所以我需要一个HashMap,它首先加载我的值,然后在其他类中使用这个映射Java 我想用SpringBoot设置一个HashMap,然后在其他类中获取下一个值,java,spring,spring-boot,hashmap,Java,Spring,Spring Boot,Hashmap,我正在使用SpringBoot,需要加载一个HashMap,其中包含一些来自类a的值 然后,我需要从类B、类C等的HashMap中获取值 所以我需要一个HashMap,它首先加载我的值,然后在其他类中使用这个映射 谢谢。我假设您有一个创建并返回SpringBean的配置类 import org.springframework.context.annotation.*; @Configuration public class MyConfiguration { /* Feel free
谢谢。我假设您有一个创建并返回SpringBean的配置类
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*/
}
import org.springframework.context.annotation.*;
@配置
公共类MyConfiguration{
/*可以随意更改地图中键和值的类型
*从字符串,字符串到您选择的任何内容
*/
@豆子
公共地图myMap(){
java.util.Map Map=new java.util.HashMap();
地图。放置(“你好”,“世界”);
返回图;
}
/*您的其他bean导出方法*/
}
一旦完成,您就可以将此映射注入任何Spring组件或服务
@Component
public class Foo {
@Autowired
private Map<String, String> myMap;
/* You can even put the annotation on a setter */
}
@组件
公开课Foo{
@自动连线
私人地图myMap;
/*您甚至可以将注释放在setter上*/
}
现在,您尝试加载的值可以是静态的,也可以是动态的(从DB)
用于静态数据
@Configuration
public class MyConfig {
@Bean
public Map<String, String> myVal(){
Map<String, String> map = new HashMap<String, String>();
map.put("Sample", "Value");
return map;
}
}
您的bean可以在任何其他类中使用。将其作为bean-in组件加载,当您需要HashMap时,只需自动连接此组件即可显示您尝试过的代码
@Autowired
private Map<String, String> myVal;
<bean class="com.example.DbConfigLoader" init-method="initMethod">
@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;
}
}