SpringMVC通过注解加载properties配置文件

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;
	}

    //此处略去万余行代码
    //……
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值