在 Spring Boot 中,可以使用 @Value 注解来将属性值注入到 Bean 的成员变量中。@Value 注解可以用于将配置文件中的属性值注入到 Bean 中。以下是一个示例:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyBean {
    @Value('${my.property}')
    private String myProperty;

    // Getter and Setter for myProperty

    // Other methods
}

在上面的示例中,@Value('${my.property}') 注解将配置文件中名为'my.property' 的属性值注入到 MyBean 类的 myProperty 成员变量中。在配置文件中,可以使用以下方式定义属性值:

my.property=Hello World

在其他类中,可以通过 @Autowired 注解将 MyBean 注入为依赖:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MyRunner implements ApplicationRunner {
    private final MyBean myBean;

    @Autowired
    public MyRunner(MyBean myBean) {
        this.myBean = myBean;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(myBean.getMyProperty()); // Output: Hello World
    }
}

在上面的示例中,MyRunner 类通过构造函数注入了 MyBean 类的实例,并在 run 方法中使用 getMyProperty 方法获取成员变量的值。

使用 Arthas 查看 Spring Boot 容器内 @Value 注解注入 Bean 的成员变量,可以使用 inspect 命令。例如:

# 启动 Arthas
java -jar arthas-boot.jar

# 查看 MyBean 类
inspect -d MyBean

# 查看 myProperty 成员变量的值
inspect -d MyBean -s myProperty

输出结果将显示 myProperty 成员变量的值,即配置文件中定义的 'Hello World'。

使用 Arthas 可以方便地查看 Spring Boot 容器内 Bean 的成员变量的值,这对排查问题和调试代码非常有用。

Arthas 查看 Spring Boot 容器内 @Value 注解注入 Bean 的成员变量

原文地址: https://www.cveoy.top/t/topic/p7iM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录