SpringBoot 从配置文件(properties)读取 map 和 list

  • application-list.properties
map.tool.cmt=fehuang2
map.tool.cmc=jieb
map.tool.slim=chzhang
map.tool.gfc=leich3

map.itl.Jack=jackc2
map.itl.Iris=yili8
map.itl.Panda=pandax
map.itl.Adun=gengwang
map.itl.Caedmon=chuankwa
  • 读取配置文件的类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@PropertySource(value = "classpath:application-list.properties")
@ConfigurationProperties(prefix = "map")
public class RelatedPerson {

    private Map tool = new HashMap<>();

    private Map itl = new HashMap<>();

    public Map getTool() {
        return tool;
    }

    public void setTool(Map tool) {
        this.tool = tool;
    }

    public Map getItl() {
        return itl;
    }

    public void setItl(Map itl) {
        this.itl = itl;
    }
}
  • 在其他类中可以通过 @Autowired 注入的方式使用
@Service
@Transactional
public class SparkBotService {
    private static final Logger logger = LoggerFactory.getLogger(SparkBotService.class);
    
    @Autowired
    private RelatedPerson relatedPerson;

    private static Map map = new HashMap<>();

    @PostConstruct
    public void init() {
        map.putAll(relatedPerson.getItl());
        map.putAll(relatedPerson.getTool());
    }
}

你可能感兴趣的:(SpringBoot 从配置文件(properties)读取 map 和 list)