spring项目有多种方式加载properties配置文件,这里选取其中一种自认为比较简便的方式进行记录。
1.在spring的全局xml中配置properties文件的路径与对应的配置类包扫描路径
spring applicationContext.xml:
<!-- 其他类扫描路径 -->
<context:component-scan base-package="com.x.y.z"/>
<!-- …… -->
<!-- 配置类扫描路径 -->
<context:component-scan base-package="com.a.b.c"/>
<!-- properties配置文件路径,多个以逗号分隔 -->
<context:property-placeholder
location="classpath:config/configxxx.properties
,classpath:myconfig/configooo.properties"
ignore-unresolvable="true"/>
2.创建配置类
在包“com.a.b.c”中创建配置类,姑且叫它“XxConfig”:
package com.a.b.c;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 配置类
* @author meiJJdewendesi
*
*/
@Component
public class XxConfig {
/**
* 某某配置
* aa、bb、cc对应properties文件中的字段名
*/
@Value("${aa}")
public String da;
@Value("${bb}")
public String db;
@Value("${cc}")
public String dc;
}
注意注解的使用姿势!
3.使用
在需要的java类中通过注解引入XxConfig类,注意该类自己也要有spring的类注解,常见的是“@Service”、“@Controller”和“@Repository”等等,实在不知道注解个啥,就用“@Component”。尽量在Service层使用,如:
/**
* Service层接口实现类
* @author meiJJdemadugong
*
*/
@Service("iXxService")
public class XxServiceImpl implements XxService {
private X x = new X();
@Autowired
private XxConfig config; //参数配置实例
//用它!
@Override
public boolean initConfig(){
if(null != this.config){
//这里示例一下把配置类实例作为参数传递下去
x.init(config);
//也可以直接使用它的属性
System.out.println("配置文件中的字段aa值为:" + config.da);
return true;
}
return false;
}
//此处略去万余行代码
//……
}