前言
在Spring框架中,@Value注解是一个非常有用的特性,它允许你将外部的值(如配置文件中的值)动态地注入到你的bean属性中。这对于配置数据库连接信息、服务URL、以及其他需要在运行时动态改变的设置非常有用。
一、@Value注解
@Value注解可以应用于字段、setter方法或构造器参数上。当Spring容器启动时,它会查找与@Value注解中指定的键(key)相匹配的属性值,并将其注入到相应的字段或方法中。
application.properties
app.name=MySpringApp
app.description=This is a Spring Boot application
你可以使用@Value注解来注入这些值到你的Spring组件中:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Value("${app.name}")
private String appName;
@Value("${app.description}")
private String appDescription;
// Getter 和 Setter 方法