1、配置項目
在apollo管控臺新增項目,並增加配置項
1.1、已有配置快速遷移
- 建議把原先配置先轉爲properties格式,然後通過Apollo提供的文本編輯模式全部粘帖到應用的application namespace,發佈配置
- 把原先的配置文件如bootstrap.properties/yml, application.properties/yml從項目中刪除
- 如果需要保留本地配置文件,需要注意部分配置如server.port必須確保本地文件已經刪除該配置項
2、添加依賴
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.4.0</version>
</dependency>
3、加入spring管理
新增以下類,並被spring掃描到
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableApolloConfig
public class ApolloConfig {
}
4、配置項目id,及apollo地址
新增文件classpath:/META-INF/app.properties,並添加以下內容
#project id in apollo
app.id=demo-project
#apollo address
apollo.meta=http://192.168.1.2:8085,http://192.168.1.3:8085
目錄層級如下:
src ├── main ├── resources ├── META-INF ├── app.properties
5、在項目中使用配置
5.1、通過api方式
Config config = ConfigService.getAppConfig();
String value = config.getProperty("spring.datasource.password", "123456");
5.2、在spring配置文件中使用
在配置文件中直接用${key}即可注入配置
<dubbo:consumer timeout="${spring.dubbo.consumer.timeout}"/>
也可指定默認值,當配置不存在時,如果沒有默認值將會報錯
<dubbo:consumer timeout="${spring.dubbo.consumer.timeout:3000}"/>
6、參考文檔
更多使用方式請參考:https://github.com/ctripcorp/apollo/wiki/Java%E5%AE%A2%E6%88%B7%E7%AB%AF%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97