Spring框架下系统常量值这样设计,使用起来超爽

常情应用

一般情况下,spring应用的常量可以通过如下样式读取配置文件内的值

/**
 * 系统常量
 */
@Configuration
@PropertySources(@PropertySource(value = "classpath:/app.properties", ignoreResourceNotFound = true, encoding = "UTF-8"))
@Data
public class AppConstants {}

但这样有个问题,要在调用方使用时则需要@autowrited注入方式,如:

@Autowired
private AppConstants appConstants;

这个样子就不是很方便了,完全没有AppConstants.AA_BB这样的来得爽,这样子spring给我们提供了一个方案,如

/**
 * 系统常量
 */
@Configuration
@PropertySources(@PropertySource(value = "classpath:/app.properties", ignoreResourceNotFound = true, encoding = "UTF-8"))
@Data
public class AppConstants {
	@Value("${out_system_url}")
    private String outSystemUrl;//注意这里不能是static,原因spring的@Value值设置不支持static属性,当然这里属性名不一定跟${out_system_url}同名也可以是别的,你喜欢的名字
	private static String OUT_SYSTEM_URL;
	
    @PostConstruct()//此注解是在outSystemUrl被设值后执行
    public void init() {
    	OUT_SYSTEM_URL = outSystemUrl;
    }
}

这个样子后,我们就能够方便的使用AppConstants.OUT_SYSTEM_URL,不需要在调用方@autowired了

高级应用

上面的一般情况是读取properties文件或yml文件的设置内容,如果我需要读取数据库的内容怎么办?什么配置要从数据库里读取?比如系统一些字典值。
这一类高级应用可以这样子来:

@Configuration
public class SysConstant {
	@Autowired
    private AppTypeService appTypeService ;//字典值
    @PostConstruct()
    public void init() {
	List<AppType> allTypes = appTypeService .getAllTypes();
	TypeConstant.initProperties(allTypes);
    }
}
###################################
public  class TypeConstant{
    private static Map<String, AppType> TYPE_KEY_VAL= new HashMap<String, AppType>();
     
    public static void initProperties(List<AppType> allTypes ) {
		for (AppType a: allTypes ) {
	    	TYPE_KEY_VAL.put(a.getType(), a);
		}
    }
    public static boolean hasAppType(String type){
    	return TYPE_KEY_VAL.containsKey(type);
    }
}

上面的例子是应用启动时从数据库中加载系统字典或常数值,减少在后面的代码里从数据库查找的过程。
拿到Type字典值集后就可以方便的TypeConstant.hasAppType("a")了,无需再在每个调用类里写下面的代码

@autowired
private AppTypeService appTypeService ;
//然后在方法里
public boolean hasType(String type){
AppType type = appTypeService.findByType(type);
if(type !=null)return true;
else return false;
}

而只需TypeConstant.hasAppType(“type”)
是不是很方便?当然要注意AppType新增修改的信息同步
高版本spring框架还可以根据前缀(prefix)进行读取

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值