@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 文件
测试代码不变
结果

posted @ 2021-07-08 23:19  蔚蓝的海洋  阅读(115)  评论(0编辑  收藏  举报