spring 引入外部资源文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhouchenxuan/article/details/82726375

开发过程中,经常使用到*.properties资源文件,其实可以把它们放在项目之外的某个地方,方便统一管理,尤其是很多项目的时候。
贴代码:
springmvc-config.xml

<!--1、在spring配置文件中加入下面代码-->
<context:property-placeholder file-encoding="utf-8"
                              location="file:E:/test/test.properties"/>

2、再新建一个类,专门存放这些属性
AppProperties.java
(如果不使用@Data @ToString,需要自行生成getter setter)

package com.zcx.resource;

import lombok.Data;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;

@Data
@ToString
public class AppProperties {
    @Value("${my.name}")
    private String name;
}

springmvc-config.xml

<!--3、回到spring配置文件,定义刚才的类-->
<bean id="appProperties" class="com.zcx.resource.AppProperties"/>

然后就可以使用了
MainController.java

// 4、引入
@Resource(name = "appProperties")
private AppProperties appProperties;

// 5、使用
@RequestMapping("/printName")
public void printName() {
    System.out.println(appProperties.getName());
}

猜你喜欢

转载自blog.csdn.net/zhouchenxuan/article/details/82726375
今日推荐