.properties文件是一种常用的KEY-VALUE键值对形式的配置文件。
spring通过加载配置文件获取键值对,然后value值赋予给和key对应的属性上,从而使得程序能运用到这个配置属性。
下面看一下例子:
user.properties配置文件
user.username=yangjiachang user.password=yjcyjcyjc
spring配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="locations" > <list> <value>classpath*:props/user.properties</value> </list> </property> </bean>
测试类:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by yangjiachang on 2016/7/22. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring-context.xml") public class PropertiesDemoTest extends AbstractJUnit4SpringContextTests { @Value("${user.username}") private String username; @Value("${user.password}") private String password; @Test public void test(){ System.out.println(username); System.out.println(password); } }
运行结果:
yangjiachang
yjcyjcyjc
以上说明已经通过注解的方式成功的从user.properties配置文件中取得了对应的值。
实际上,原理也是通过spring注入的方式实现的,默认情况下,spring注入的为单例,因此只有该实例会根据配置赋值,new出来的实例是没有的。