@Value 和 @PropertySource 注解

2021/7/8 23:36:52

本文主要是介绍@Value 和 @PropertySource 注解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

@Value 注解赋值

直接给成员变量赋值

Person 类

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
    @Value("张三")
    private String name;
    @Value("18")
    private Integer age;
}

在 Person 类中,为 name 字段和 age 字段分别做了赋值操作
配置类

@Configuration
public class ValueConfig {

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

在配置类中,并没有调用 person 对象的 setter 方法,只是创建了一个对象
测试代码

@Test
public void test10() {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(ValueConfig.class);
    Person person = ctx.getBean(Person.class);
    System.out.println(person);
}

直接来看 输出结果

@PropertiesSource 注解配置

直接从 properties 文件中读取

从 properties 文件直接读取配置时,我们需要加载 properties 文件到 IoC 容器中,这时就需要使用 @PropertiesSource 注解告诉 Ioc 容器,properties 文件的位置。在配置类中配置。
properties 文件中的内容

person.name=李四
person.age=30

Person 类

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;
}

配置类

@Configuration
@PropertySource("classpath:/source.properties")
public class ValueConfig {

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

}

此时使用 @PropertySource 注解加载 properties 文件
测试代码不变
结果



这篇关于@Value 和 @PropertySource 注解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程