spring-cloud-alibaba 最新版本 2021.0.1.0
問題描述
項目啟動無報錯,但是不能讀取到 Nacos 中配置的數據,而且似乎是根本沒有連接到Nacos(注冊中心功能可以正常注冊),因為如果注釋掉application.propertis
中的屬性 coupon.user.name 則會直接報錯,提示@Value("${coupon.user.name}") 讀不到配置;
Nacos Config Starter 實現了 org.springframework.cloud.bootstrap.config.PropertySourceLocator接口,並將優先級設置成了最高。
在 Spring Cloud 應用啟動階段,會主動從 Nacos Server 端獲取對應的數據,並將獲取到的數據轉換成 PropertySource 且注入到 Environment 的 PropertySources 屬性中,所以使用 @Value 注解也能直接獲取 Nacos Server 端配置的內容。
根據上面官方例子中的原理的說明 Nacos Config Starter 實現PropertySourceLocator接口,而我在其實現類中debug並沒有執行,由此判斷是可能沒有連接Nacos。
解決
原因是 最新版本(2021.0.1.0)移除了 spring-cloud-starter-bootstrap 的支持,改用 spring.config.import
解決方法: https://github.com/alibaba/spring-cloud-alibaba/pull/2349
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<!-- 排除 bootstrap, 未來版本 spring-cloud-alibaba 應該在 spring boot >= 2.4.0 時將該依賴設置為 optional -->
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</exclusion>
</exclusions>
</dependency>
# application.yml (不能是bootstrap.yml)
spring:
cloud:
nacos:
config:
group: DEFAULT_GROUP
server-addr: localhost:8848
config:
import:
- optional:nacos:test.yml # 監聽 DEFAULT_GROUP:test.yml
2021.0.1.0 Latest
⭐️ Features / Enhancements
[Nacos Config] Support spring.config.import (#2349 )
[Nacos Config] Remove dependency spring-cloud-starter-bootstrap (#2349 )
更多關於這個問題的描述見 https://segmentfault.com/q/1010000041610909