spring autowired 配置properties

<beans:bean id="nfsqProperties"

class="org.springframework.beans.factory.config.PropertiesFactoryBean">

<beans:property name="locations">

<beans:list>

<beans:value>/WEB-INF/spring/*.properties</beans:value>

<beans:value>/WEB-INF/sap/*.properties</beans:value>

</beans:list>

</beans:property>

</beans:bean>

定义bean 使用PropertiesFactoryBean

然后

@Autowired

private Properties nfsqProperties;

Spring 框架中,除了可以自定义数据源(如上文提到的 `DataSource`),还可以通过 `@ConfigurationProperties` 注解将自定义的 `properties` 配置信息绑定到 Java Bean 中。这种做法非常适合用于加载和管理应用中的配置参数。 --- ### 问题描述 如何在 Spring Boot 中读取自定义的 `properties` 文件中的配置,并将其映射为一个 Java 对象? --- ### 解决方案:使用 `@ConfigurationProperties` 映射自定义配置 #### 1. 在 `application.properties` 中添加自定义配置 ```properties # 自定义配置项 app.config.title=My Custom Application app.config.version=1.0.0 app.config.enabled=true app.config.max-connections=50 ``` #### 2. 创建一个 Java Bean 来接收这些配置 ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "app.config") public class AppConfig { private String title; private String version; private boolean enabled; private int maxConnections; // Getters and Setters public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getMaxConnections() { return maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } } ``` #### 3. 使用这个配置类(例如在 Controller 中) ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AppController { @Autowired private AppConfig appConfig; @GetMapping("/config") public String getConfig() { return "Title: " + appConfig.getTitle() + "<br>" + "Version: " + appConfig.getVersion() + "<br>" + "Enabled: " + appConfig.isEnabled() + "<br>" + "Max Connections: " + appConfig.getMaxConnections(); } } ``` --- ### 解释说明 - **`@ConfigurationProperties`**:该注解用于将配置文件中具有相同前缀的属性自动映射到 Java Bean 的字段中。 - **`prefix = "app.config"`**:表示只匹配以 `app.config` 开头的属性。 - **`@Component`**:确保该类被 Spring 容器管理,成为一个 Bean。 - **类型安全注入**:Spring 会自动进行类型转换,比如字符串转布尔、整数等。 - **Getters 和 Setters**:必须提供这些方法,Spring 才能正确地设置值。 > 注意:如果你使用的是 Spring Boot 2.4 及以上版本,还需要在主类或配置类上加上 `@EnableConfigurationProperties` 注解来启用配置属性支持(不过通常默认已启用)。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值