七、Spring注解:@value & @PropertySource

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/liujun03/article/details/81872353

一、@Value注解

​ 使用@Value注解给组件注入属性值,可以极大的简化项目配置。当使用JavaConfig方式配置bean的时候,@Value基本有三种使用方法:

​ ①:赋值基本数值

​ ②:可以写SpEL 即#{}

​ ③:可以写 ${},去取出配置文件中的值

​ 当使用XML方式配置bean的时候,我们可以使用property属性给组件注入属性值:

<bean id="person" class="com.baiding.model.Person" scope="prototype">
        <property name="name" value="lisi"/>
        <property name="age" value="23"/>
</bean>

此时,我们可以使用@Value注解来代替这种用法:

public class Person {
    @Value("liming")
    private String name;
    @Value("#{20-9}")
    private Integer age;

    // ......

写个配置类进行测试:

@Configuration
public class PersonConfig {
    @Bean
    public Person person(){
        return new Person();
    }
}

测试类:

    @Test
    void test08(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(ValueConfig.class);
        Person person = (Person) ac.getBean("person");
        System.out.println(person);
    }

    // 测试结果
    // Person{name='liming', age=11}
测试结果可以看出,基本数值赋值 和 Spring表达式赋值都成功了。

二、@PropertySource注解

​ Spring提供的@PropertySource注解主要是用来加载指定的属性文件,相当于原来在XML文件中配置的:

<context:property-placeholder location="classpath:/person.properties"/>

首先我们在类路径下建立一个properties属性文件:person.properties

里面只有一行数据

person.nickName=Nick

接下来 就是使用@PropertySource将person.properties加载到环境中:

@Configuration
//@PropertySource(value = {"classpath:/person.properties"})
@PropertySource(value = "classpath:/person.properties")
public class ValueConfig {

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

上述代码建立了一个配置类,并在类上添加了@PropertySource注解,@PropertySource注解的value值可以是一个字符串也可以是一个数组,是数组的时候就是同时加载多个属性文件了。

之后改造一下上述的person类:

public class Person {
    @Value("liming")
    private String name;
    @Value("#{20-9}")
    private Integer age;

    @Value("${person.nickName}")
    private String nickName;

    public Person() {}

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

可以看到在属性nickName上面使用了注解@Value引入了环境变量person.nickName。

最后测试一下,看看引用成功没有:

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

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

输出的结果:

Person{name='liming', age=11, nickName='Nick'}
Nick
从结果可以看出,属性文件中的属性值成功赋值到了person类的nickName属性中去。所以说@Value可以使用${}方式去引用属性文件的数据。在测试方法的最后还得到了上下文的环境,可以看出属性文件中的值在使用@PropertySource注解加载完之后,是将数据注册到了上下文环境中的。

猜你喜欢

转载自blog.csdn.net/liujun03/article/details/81872353