版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/changyayun/article/details/81747827
本次实验室为了测试@Value注解是在什么时候起效的
下面是程序详情:
配置文件 study.properties
study=123
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: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">
<context:annotation-config/>
<bean id="beanInit" class="com.study.BeanInit" init-method="init" destroy-method="destory"></bean>
<bean id="beanAnnotation" class="com.study.BeanAnnotation">
<property name="name" value="cyy"></property>
<!--<property name="code" value="${study}"></property>-->
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:study.properties</value>
</list>
</property>
</bean>
</beans>
BeanAnnotation.java
public class BeanAnnotation {
private String init;
private String name;
@Value("${study}")
private String code;
public String getName() {
return name;
}
{
init = "lyx";
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
我这边通过两种方式对比:
name属性都是通过在properties中配置
1.code属性在properties中配置时,Spring在实例化bean后,对bean的属性进行配置,配置顺序是按照xml中properties的指定顺序,先设置name的值后设置code的值。
2.code并不在properties中配置,而是通过@Value注解配置。通过单步调试,使用注解时code属性的注入时机也是在Spring在实例化bean后,但是他是在name之前就已经赋值了。
这里我为什么肯定@Value也是在spring对bean实例化之后,配置属性时生效的,因为我加了一行
{
init = "lyx";
}
这个代码块就是在bean对象实例化的时候执行的。程序执行的顺序是先进入<init>,此时code为null
然后程序进入setName函数,而进入setName时,code已经有值。