前面已经实现了将加密的属性取出并解密!对于某些属性不方便让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对象的。