@Value 注入属性值

本次实验室为了测试@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已经有值。这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值