springboot 打印springProperty的值
在Spring Boot中,你可以使用@Value
注解来打印Spring Property的值。这个注解可以将配置文件中的值注入到Spring管理的Bean的字段中。
以下是一个简单的例子,演示如何打印Spring Property的值:
-
在
application.properties
或application.yml
中定义一个属性:# application.properties app.greeting=Hello, Spring!
或者使用YAML格式:
# application.yml app: greeting: Hello, Spring!
-
创建一个Spring组件,并使用
@Value
注解来注入属性值:import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyComponent { @Value("${app.greeting}") private String greeting; public void printGreeting() { System.out.println(greeting); } }
-
在你的主应用类或任何其他Spring管理的Bean中调用
printGreeting
方法: -
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyAppRunner implements CommandLineRunner { private final MyComponent myComponent; @Autowired public MyAppRunner(MyComponent myComponent) { this.myComponent = myComponent; } @Override public void run(String... args) { myComponent.printGreeting(); } }
当你运行Spring Boot应用时,
MyAppRunner
会在命令行中打印出app.greeting
属性的值。