Spring使用Properties文件

1.Properties文件的内容

dbName=sampledb
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/${dbName}
#userName=root
#password=1234
userName=WnplV/ietfQ=
password=gJQ9O+q34qk\=

 2.Spring配置 

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<!--1.使用传统的PropertyPlaceholderConfigurer引用属性文件  -->
	<!--
		bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		p:fileEncoding="utf-8"> <property name="locations"> <list>
		<value>classpath:com/baobaotao/placeholder/jdbc.properties</value>
		</list> </property> </bean
	-->
	
	<!--2.使用context命名空间的配置引用属性文件  -->
	<!--context:property-placeholder
		location="classpath:com/baobaotao/placeholder/jdbc.properties" file-encoding="utf8"/>
	<bean id="utf8" class="java.lang.String">
		<constructor-arg value="utf-8"></constructor-arg>
	</bean-->

	<!--3.使用加密版的属性文件  -->
	<bean class="com.baobaotao.placeholder.EncryptPropertyPlaceholderConfigurer"
	    p:location="classpath:com/baobaotao/placeholder/jdbc.properties"
		p:fileEncoding="utf-8"/>

    <context:component-scan base-package="com.baobaotao.placeholder"/>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" p:driverClassName="${driverClassName}" p:url="${url}"
		p:username="${userName}" p:password="${password}" />
</beans>

 3.加密的java Class文件EncryptPropertyPlaceholderConfigurer.java

 

 

package com.baobaotao.placeholder;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {	
	private String[] encryptPropNames ={"userName","password"};
	
	@Override
	protected String convertProperty(String propertyName, String propertyValue) {		
		if(isEncryptProp(propertyName)){
			String decryptValue = DESUtils.getDecryptString(propertyValue);
			System.out.println(decryptValue);
			return decryptValue;
		}else{
			return propertyValue;
		}
	}
	
	/**
	 * 判断是否是加密的属性
	 * @param propertyName
	 * @return
	 */
	private boolean isEncryptProp(String propertyName){
		for(String encryptPropName:encryptPropNames){
			if(encryptPropName.equals(propertyName)){
				return true;
			}
		}
		return false;
	}
}

 

 

使用到的加密工具DESUtils.java

package com.baobaotao.placeholder;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESUtils {
	private static Key key;
	private static String KEY_STR = "myKey";
	static {
		try {
			KeyGenerator generator = KeyGenerator.getInstance("DES");
			generator.init(new SecureRandom(KEY_STR.getBytes()));
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对str进行DES加密
	 * 
	 * @param str
	 * @return
	 */
	public static String getEncryptString(String str) {
		BASE64Encoder base64en = new BASE64Encoder();
		try {
			byte[] strBytes = str.getBytes("UTF8");
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptStrBytes = cipher.doFinal(strBytes);
			return base64en.encode(encryptStrBytes);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对str进行DES解密
	 * 
	 * @param str
	 * @return
	 */
	public static String getDecryptString(String str) {
		BASE64Decoder base64De = new BASE64Decoder();
		try {
			byte[] strBytes = base64De.decodeBuffer(str);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decryptStrBytes = cipher.doFinal(strBytes);
			return new String(decryptStrBytes, "UTF8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	public static void main(String[] args) throws Exception {
//		if (args == null || args.length < 1) {
//			System.out.println("请输入要加密的字符,用空格分隔.");
//		} else {
//			for (String arg : args) {
//				System.out.println(arg + ":" + getEncryptString(arg));
//			}
//		}
		
		System.out.println(getDecryptString("WnplV/ietfQ="));
		System.out.println(getDecryptString("gJQ9O+q34qk="));
	}
}

 

 

4.在基于注解的java类中使用属性

package com.baobaotao.placeholder;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

@Component
public class MyDataSource {
    @Value("${driverClassName}")
	private String driverClassName;
    
    @Value("${url}")
	private String url;
    
    @Value("${userName}")
	private String userName;
    
    @Value("${password}")
	private String password;
    
    public String toString(){
    	 return ToStringBuilder.reflectionToString(this);
    }	
}

 

 

 

### 回答1: Spring可以通过`PropertyPlaceholderConfigurer`来读取properties文件。 1. 在Spring配置文件中添加`PropertyPlaceholderConfigurer`的bean: ```xml <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> </bean> ``` 2. 在properties文件中定义属性: ```properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=123456 ``` 3. 在Spring配置文件使用属性: ```xml <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> ``` 这样就可以通过Spring读取properties文件中的属性了。 ### 回答2: Spring 是一个广泛使用的框架,受欢迎的一个原因是其简化了很多任务。其中之一就是读取 properties 文件。在 Spring 中,我们不必自己编写代码从文件中读取属性。我们可以利用 Spring 的功能来自动读取属性,使得我们可以更加专注于应用程序的业务逻辑,并且遵循 Spring 管理原则。 Spring 提供了多种读取 properties 文件的方式。下面是其中的几种常见方式: 1. 使用 @Value 注解 @Value 注解本质上将属性文件的值注入到我们的 Java 类中。例如,我们可以在 Spring 的配置文件中定义以下属性值: application.properties ```properties app.name=My Application app.version=1.0 ``` 然后在我们的 Java 类中,在需要的属性前面加上 @Value 注解即可。 ```java @Component public class MyComponent { @Value("${app.name}") private String appName; @Value("${app.version}") private String appVersion; // ... } ``` 2. 使用 PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer 是一个特殊的 bean,它读取属性文件并将属性值注入到其他 bean 中。配置方式如下: ```xml <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/application.properties</value> </list> </property> </bean> ``` 然后,在 Java 类中可以使用 @Value 注解获取属性值。 3. 配置文件的统一管理 Spring 还提供了一个功能来统一管理配置文件。每个应用程序可能需要多个配置文件,所以 Spring 提供了一种方法来将这些配置文件合并为一个层次结构。这种方式称为 “Environment Abstraction”,它允许应用程序使用一组由多个配置文件组成的 “属性源”。 ```java @Configuration @PropertySource("classpath:/application.properties") public class AppConfig { @Autowired Environment env; @Bean public MyComponent myComponent() { MyComponent component = new MyComponent(); component.setAppName(env.getProperty("app.name")); component.setAppVersion(env.getProperty("app.version")); return component; } } ``` 以上是 Spring 读取 properties 文件的常见方式。开发者可以根据自己的需求选择不同的方式。无论选择哪种方式,Spring 已经为我们创建了属性文件读取的底层机制和简化方式,使得我们更加便利地开发。 ### 回答3: Spring读取properties文件是很常见的操作,通常我们会在配置文件中声明需要读取的文件路径,并通过注入的方式将文件中的内容读取到Spring的环境中。以下是更详细的步骤: 1. 确定properties文件的存储位置和名称。可以将其放置在classpath下或者指定文件路径。这里假设放在classpath下,文件名为config.properties。 2. 在Spring的配置文件使用以下语句引用这个properties文件: ``` <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> </bean> ``` 这里使用Spring提供的“PropertyPlaceholderConfigurer”类。这个类允许我们将properties文件的内容注入到Spring的环境中。 3. 在需要读取properties文件的类中注入这个“PropertyPlaceholderConfigurer”对象,并使用以下语句读取其中的值: ``` @Value("${key}") private String value; ``` 其中,key是properties文件中的键名,value则为其对应的值。 另外,还可以通过“ResourceBundleMessageSource”类直接读取properties文件中的文本资源,例如: ``` ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("config"); String message = messageSource.getMessage("key", null, Locale.getDefault()); ``` 这里使用Spring提供的“ResourceBundleMessageSource”类,将properties文件中的文本资源转换为字符串类型的message。 总之,读取properties文件Spring开发中一个比较基础的操作,熟练掌握此技能可以提高代码开发效率,并且为系统开发提供清晰的配置方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值