第一种方式:使用Properties来读取配置
创建输入流,读取配置文件路径,利用Properties对象来加载输入流,然后根据Properties的方法来取到配置文件的对应key值就行。具体代码如下:
InputStream input = Test.class.getResourceAsStream("/config/test.properties");
Properties paro=new Properties();
paro.load(input);
String name=paro.getProperty("name");
System.out.println(name);
input.close();
第二种方式:使用Spring注解来读取配置
添加以下配置:
<bean id="test" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<array>
<value>classpath*:/config/test.properties</value>
</array>
</property>
</bean>
创建对应的bean对象
@Component("user")
public class user {
private String name;
public String getName() {
return name;
}
@Value("#{test['name']}") 或者@Value("#{test.name}")
public void setName(String name) {
this.name = name;
System.out.println("user的值为:"+name);
}
}