使用PropertyPlaceholderConfigurer读取.properties文件(3)-公共类获取属性

前面已经实现了将加密的属性取出并解密!对于某些属性不方便让spring自动注入,只是想自己去调用,这个时候就需要用到在CustomPropertyConfigurer类中的getProperty()的方法。如果有很多的属性都需要手动取,那么就可以做一个公共类。

constants.java

package org.demo.constants;

import org.demo.util.CustomPropertyConfigurer;

public interface Constants {
	/**
	 * 员工属性
	 */
	String empName = CustomPropertyConfigurer.getProperty("emp.name");
	int empAge = Integer.parseInt(CustomPropertyConfigurer.getProperty("emp.age"));
	char empGender = CustomPropertyConfigurer.getProperty("emp.gender").charAt(0);
	String empPassword = CustomPropertyConfigurer.getProperty("emp.password");

	//如果有更多属性可以继续向下写
}

如此就可以很方便的取到属性了,看下面的测试类:

import org.apache.log4j.Logger;
import org.demo.constants.Constants;
import org.demo.model.EmpModel;
import org.demo.util.CustomPropertyConfigurer;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class GetBeanTest {
	private static final Logger logger = Logger.getLogger(GetBeanTest.class);
	ApplicationContext ac;
	
	/** 实例化ApplicationContext */
	@Before
	public void init() {
		ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	
	/** 自动注入的方法 */
	@Test
	public void getEmpModelBean1(){
		EmpModel emp = ac.getBean("empModel",EmpModel.class);
		logger.info("emp.name:"+CustomPropertyConfigurer.getProperty("emp.name"));
		logger.info(emp);	
	}	
	
	/** 手动创建对象的方法 */
	@Test
	public void getEmpModelBean2(){
		EmpModel emp = new EmpModel();
		emp.setName(Constants.empName);
		emp.setAge(Constants.empAge);
		emp.setGender(Constants.empGender);
		emp.setPassword(Constants.empPassword);
		logger.info(emp);
	}
}

**成功!调用getEmpModelBean2()前,也是需要实例化ApplicationContext对象的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值