@Value和@ConfigurationProperties

 @Value

 @Value("${student.age:18}")

@ConfigurationProperties 

class:
  classroom: 501
  student:
    name: murphy
    age: 25
@Data
public class Student {
    private String name;
    private Integer age;
}
@Data
@Component
@ConfigurationProperties(prefix = "class")
public class StudentProperties {
    private String classroom;
    private Student student = new Student();
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestController {
    @Autowired
    private StudentProperties studentProperties;

    @org.junit.Test
    public void test() {
        System.out.println(studentProperties.getStudent().getAge());
        System.out.println(studentProperties.getStudent().getName());
        System.out.println(studentProperties.getClassroom());
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@ConfigurationProperties 和 @Value 可以混合使用,但需要注意以下几点: 1. 需要在类上添加 @ConfigurationProperties 注解,并指定前缀,用于将配置文件中的属性值注入到类的属性中。 2. 在需要使用 @Value 注解的属性上添加该注解,并指定属性的名称,用于将指定的属性值注入到该属性中。 3. 如果使用 @Value 注解的属性在配置文件中没有对应的值,则会报错,因此需要设置默认值或者使用 required 属性来避免报错。 4. 如果使用 @Value 注解的属性和 @ConfigurationProperties 注解指定的属性名称相同,则 @Value 注解的属性值会覆盖 @ConfigurationProperties 注解指定的属性值。 下面是一个示例代码: ```java @ConfigurationProperties(prefix = "example") public class ExampleProperties { private String name; private int age; // 省略 getter 和 setter 方法 @Override public String toString() { return "ExampleProperties{" + "name='" + name + '\'' + ", age=" + age + '}'; } } @Component public class ExampleComponent { @Value("${example.name:defaultName}") private String name; @Autowired private ExampleProperties properties; public void printProperties() { System.out.println("name from @Value: " + name); System.out.println("name from @ConfigurationProperties: " + properties.getName()); System.out.println("age from @ConfigurationProperties: " + properties.getAge()); } } ``` 在上面的示例中,ExampleProperties 类使用 @ConfigurationProperties 注解指定了前缀为 example,用于将配置文件中以 example 开头的属性值注入到该类的属性中。ExampleComponent 类中使用 @Value 注解指定了属性 name 的值,并使用 @Autowired 注解将 ExampleProperties 类注入到该类中。在 printProperties 方法中,分别输出了从 @Value 和 @ConfigurationProperties 中获取的属性值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值