SpringBoot——使用@Value()注解获取yml字段为null

使用@Value注解获取yml字段

在Spring Boot中,可以使用@Value注解来读取和赋值YAML配置文件中的值到变量中。

如何读取YAML配置文件中的值并将其赋值给变量

示例代码:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MyApp {
    @Value("${myapp.property1}")
    private String property1;

    @Value("${myapp.property2}")
    private int property2;

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @Bean
    public void printProperties() {
        System.out.println("Property 1: " + property1);
        System.out.println("Property 2: " + property2);
    }
}

在上述示例中,我们使用@SpringBootApplication注解标识了Spring Boot应用的入口类。该类中有两个变量property1property2,分别用@Value注解进行注入和赋值。

@Value注解中,通过${}语法指定了要读取的配置文件中的属性名。例如${myapp.property1}表示要读取application.yml文件(或者是application.properties文件)中myapp.property1属性的值。您需要将属性的名称和文件类型与实际的配置文件一致。

在上面的示例中,我们创建了一个名为printProperties()@Bean方法,它在应用启动时被调用,并打印出配置文件中读取到的属性值。

确保已经在application.yml中定义了myapp.property1myapp.property2属性的值

例如:

myapp:
  property1: Hello
  property2: 123

当字段设为static时获取的为null

解决方法如下

如果将字段声明为静态(static),并且在Spring Boot应用程序中使用@Value注解来注入配置值,很可能会出现字段为null的情况。这是因为在字段静态化的情况下,Spring框架无法将配置值注入到静态字段中,因为Spring的依赖注入是在实例化bean时进行的。

如果确实需要将配置值赋值给静态字段,可以通过使用@PostConstruct注解来解决这个问题。@PostConstruct注解表示在实例化bean之后,由Spring容器调用的方法。

如何在静态字段上使用@Value注解,并在@PostConstruct方法中将值赋给该字段:

示例代码:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class MyApp {
    @Value("${myapp.property}")
    private static String property;

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @PostConstruct
    public void init() {
        property = property;
    }

    // 在其他地方可以使用静态字段property
}

在上述示例中,我们将property字段声明为静态字段,并使用@Value注解进行注入。然后,我们在init()方法上使用@PostConstruct注解,该方法在实例化bean之后被调用。在init()方法中,我们将属性的值赋给静态字段。

需要注意的是,使用静态字段可能会引入其他线程安全和并发性问题,请根据具体情况慎重使用静态字段。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值