文章目录
- 总目录
- 一、引入依赖
- 二、配置@EnableApolloConfig
- 三、配置apollo
- 四、应用, 获取apollo配置的信息
- 4.1 @Value
- 4.2 @ApolloJsonValue() 用来把配置的json字符串自动注入为对象
- 4.3 默认值
- 4.4 未配置key, 且代码中未设置默认值,会编译失败
必要前提apollo服务已经正常启动
一、引入依赖
implementation 'com.ctrip.framework.apollo:apollo-client:2.1.0'
二、配置@EnableApolloConfig
项目启动类配置@EnableApolloConfig
@EnableApolloConfig
@SpringCloudApplication
public class ShoppingOrderApplication {
public static void main(String[] args) {
SpringApplication.run(ShoppingOrderApplication.class, args);
}
}
三、配置apollo
#服务端口号
server:
port: 11004
#设置服务名称
spring:
application:
# 应用名字,eureka 会根据它作为服务id
name: shopping-order
## apollo配置
app:
#apollo 管理端页面, 手动创建应用的id
id: order-00001
apollo:
bootstrap:
enabled: true
namespaces: application
#apollo configservice服务的地址, 注意端口号后无 "/"
meta: http://localhost:2001
四、应用, 获取apollo配置的信息
默认使用apollo的管理页面已经创建了应用,且创建了order.userName、order.userInfoList
4.1 @Value
@Value("${order.userName}")
private String userName;
4.2 @ApolloJsonValue() 用来把配置的json字符串自动注入为对象
@ApolloJsonValue("${order.userInfoList}")
private List<UserInfo> userInfoList;
4.3 默认值
${order.userName:AAAA} 表示当Apollo未配置key=order.userName时候,设置AAAA为默认值
${order.userInfoList:[]} 表示当Apollo未配置key=order.userInfoList时候,设置空数组为默认值
4.4 未配置key, 且代码中未设置默认值,会编译失败
@Value("${order.userName1}")
@ApolloJsonValue("${order.userInfoList1}")
错误提示:Could not resolve placeholder 'order.userName1' in value "${order.userName1}"
下面正确使用:
package com.pd.shopping.order.controller;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.pd.shopping.order.model.bo.UserInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/hello")
public class HelloController {
@Value("${order.userName}")
private String userName;
@ApolloJsonValue("${order.userInfoList}")
private List<UserInfo> userInfoList;
@GetMapping("/testApollo")
public void testApollo() {
String a = userName;
List<UserInfo> b = userInfoList;
}
}