Spring全注解之使用@Value注解对属性赋值

前沿

我们之前再使用xml方式进行配置的时候,需要使用<property>标签对属性赋值。现在使用全注解的方式我们可以使用@value注解来赋值。

开始

创建一个person类,并加上相应的注解

/**
 * @Author 喜欢编程的夏先生
 * @Date 2022-06
 */
public class Person {
    @Value("大明")
    private String name;
    @Value("#{20-2}")
    private Integer age;
    @Value("${person.nickName}")
    private String nickName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name=" + name +  +
                ", age=" + age +
                ", nickName=" + nickName +  +
                };
    }
}

创建配置类

/**
 * @Author 喜欢编程的夏先生
 * @Date 2022-06
 */
@Configuration
@PropertySource({"classpath:person.properties"})
public class ValueConfig {

    @Bean("person")
    public Person getPerson(){
        return new Person();
    }
}

编写测试

@Test
    public void test1(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ValueConfig.class);
        Person person = ac.getBean(Person.class);
        System.out.println(person);

        ConfigurableEnvironment environment = ac.getEnvironment();
        String property = environment.getProperty("person.nickName");
        System.out.println(property);
    }

运行结果

经验分享 程序员 微信小程序 职场和发展