SpringMVC加载Properties文件

在看了网上许许多多的总结注入properties文件,总结一下其中的一种可以成功运行的例子,在多次的尝试后我觉得有必要总结一下。

我的代码是把自定义的参数注入到配置类中,然后从配置类中调用,代码如下

在开始之前因为我们要进行测试,所以引入下测试的包

pom.xml文件如下

<!-- 引入这2个测试用的包 -->
<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.12.RELEASE</version>
			<scope>test</scope>
		</dependency>

1.首先是applicationContext.xml

       (1)以下是application.xml中的一些配置导入。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

      (2)导入资源配置

<!-- 配置组件自动扫描 -->
	<context:component-scan base-package="com.xx.xxx"><!-- 这里是你自己的包名 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
<!-- 导入资源文件 -->
	<util:properties id="test" location="classpath:test.properties"/> 

2.test.properties如下

命名中不要出现 ‘-’,比如user-name,会报错,可以写成userName这种形式,方便之后的注入

name=Lucas
hobby=basketball

3.接下来是配置文件TestConfig.class

@Component
public class TestConfig {
  
  @Value("#{test.name}") 
  private String name;
  
  @Value("#{test.hobby}") 
  private String hobby;

  public String getName() {
    return name;
  }
  
  public void setName(String name) {
    this.name= name;
  }

  public String getHobby() {
    return hobby;
  }

  public void setHobby(String hobby) {
    this.hobby= hobby;
  }

}

4.我们可以写个测试类测试一下

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class ConfigTest {

	@Autowired
	private TestConfig testConfig;

	@Test
	public void checkTest(){
		System.out.println(testConfig.getName()+"-------------");
        System.out.println(testConfig.getHobby()+"-------------");
	}

}

这样就可以取到数据啦

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值