<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--包扫描 , 只要标注了 @Controller 、@Service、@Repository、@Component的类 都会被扫描-->
<context:component-scan base-package="com.hw.springannotation"></context:component-scan>
<!--导入配置文件中的属性值-->
<context:property-placeholder location="classpath:pension.properties"></context:property-placeholder>
<bean id="pension" class="com.hw.springannotation.beans.Pension" scope="prototype" init-method="" destroy-method="">
<property name="name" value="hw"></property>
<property name="age" value="18"></property>
<property name="nickName" value="${nickName}"></property>
</bean>
</beans>
// 使用@PropertySource来读取外部配置文件中的k/v值 保存到运行的环境变量中,加载完就可以使用${}取出
@PropertySource(value = {"classpath:/pension.properties"})
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Pension pension() {
return new Pension();
}
}
@Value("张三")
private String name;
@Value("#{22-1}")
private Integer age;
@Value("${nickName}")
private String nickName;
nickName=小张三
// 通过 applicationContext 获取配置文件值
String nickName = applicationContext.getEnvironment().getProperty("nickName");
System.out.println(nickName);
19、属性赋值-@PropertySource加载外部配置文件
原文:https://www.cnblogs.com/Grand-Jon/p/10038901.html