单独定义Map数据结构的bean:
<bean id= "expToLevelMap" class="org.springframework.beans.factory.config.MapFactoryBean" > <property name ="sourceMap"> <map> <entry key ="expToLevel"> <value> <![CDATA[ [{id:0, "name":"江湖小虾","level":0,"exp":0}, {id:1, "name":"江湖小虾","level":1,"exp":6}, {id:2, "name":"江湖小虾","level":2,"exp":16}, {id:3, "name":"江湖小虾","level":3,"exp":40}, {id:4, "name":"江湖小虾","level":4,"exp":70}, {id:5, "name":"江湖小虾","level":5,"exp":110}, {id:6, "name":"江湖小虾","level":6,"exp":190}, {id:7, "name":"江湖小虾","level":7,"exp":310}, {id:8, "name":"江湖小虾","level":8,"exp":470}, {id:9, "name":"江湖小虾","level":9,"exp":670}, {id:10, "name":"江湖小虾","level":10,"exp":790} ] ]]> </value> </entry> </map> </property> </bean >
property可以定义很多个,这样的方式,用spring配置就可以重用这个map里的值了。
value是一个json数组,数组中是一个exp值和level的对应关系的结构。那么我们在spring启动的时候就解析这个value,把它转成java中Object,提供给其他组件使用。
接下来要做的是解析这个value到jsonArray,再解析到object TreeMap。
所以我们在初始化bean容器的时候就进行解析:
这里使用
@PostConstruct
@Service("expToLevelService" ) public class ExpToLevelServiceImpl { @Resource private Map<String , String> expToLevelMap; private TreeMap<Long , ExpToLevelObj> expToLevelTreeMap; @PostConstruct public void init () { expToLevelTreeMap = new TreeMap<Long , ExpToLevelObj>(); JSONArray array = JSONArray.parseArray (expToLevelMap. get("expToLevel" )); for ( Object object : array) { JSONObject jsonObj = (JSONObject) JSONObject.parse (object. toString()); ExpToLevelObj obj = new ExpToLevelObj(jsonObj .getIntValue( "id"), jsonObj.getIntValue ("exp") , jsonObj.getIntValue ("level") , jsonObj .getString( "name")); expToLevelTreeMap.put (jsonObj. getLongValue("exp" ), obj); } } public TreeMap<Long , ExpToLevelObj> getExpToLevelTreeMap (){ return expToLevelTreeMap ; } }
这里又使用了TreeMap的特性,把exp(经验值)和level(等级)的对应关系放入
TreeMap后,外界想知道一个随机的exp查出在多少level,是比较方便的。
最后我们会组装好一个expToLevelTreeMap 提供出去。
所以整个过程类似读取配置文件,进行不同的配置。
ExpToLevelObj :
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class ExpToLevelObj { public ExpToLevelObj(){ } public ExpToLevelObj(int id, int exp, int level, String name){ super(); this.id = id; this.exp = exp; this.level = level; this.name = name; } private int id; private int exp; private int level; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getExp() { return exp; } public void setExp(int exp) { this.exp = exp; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
外界使用:
下面的代码就可以查出25exp,处于多少等级了
TreeMap < Long, ExpToLevelObj > treeMap = expToLevelService . getExpToLevelTreeMap (); expToLevelObj = treeMap . lowerEntry( 25) .getValue () ; expToLevelObj . getLevel()