常情应用
一般情况下,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)进行读取