@ConfigurationProperties
注解在 Spring Boot 中用于将配置文件中的属性映射到 Java 对象。它可以加在类上或方法上,具体用法如下:
1. 加在类上
当 @ConfigurationProperties
加在类上时,整个类的属性会被映射到配置文件中的相应属性。通常与 @Component
或 @Configuration
一起使用。
示例:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {private String name;private String version;// getters and setters
}
在这个例子中,app.name
和 app.version
会被映射到 AppProperties
类的 name
和 version
属性上。
2. 加在方法上
当 @ConfigurationProperties
加在方法上时,通常用于配置类中的方法,允许将配置属性注入到特定的方法中。这种方式通常用于更复杂的配置场景。
示例:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class AppConfig {@Bean@ConfigurationProperties(prefix = "app")public AppProperties appProperties() {return new AppProperties();}
}
在这个例子中,appProperties
方法返回一个 AppProperties
实例,并将配置文件中的属性映射到该实例上。
总结
- 加在类上:适合简单的属性映射,通常与
@Component
一起使用。 - 加在方法上:适合更复杂的配置场景,通常用于配置类中。
选择使用哪种方式,取决于你的具体需求和项目结构。