在Spring Boot中,环境variables和@Value不能一起工作

我有一个Spring启动应用程序,连接到作为caching工作的Redis实例。 当我在开发环境中时,我有以下几点:

--- spring: profiles: default redis: host: localhost port: 6379 

而我的cachingconfiguration类是这样的:

 @Configuration @EnableCaching public class CacheConfiguration { @Value("${redis.host}") String redisHost; @Value("${redis.port}") int redisPort; 

在生产中,这个应用程序是Docker化的,我有以下docker-compose.yml文件:

 redis: image: tutum/redis ports: - "6379:6379" volumes: - /data app: build: . ports: - "8080:8080" links: - redis 

application.yml是:

 --- spring: profiles: docker redis: host: redis port: 6379 

要在Docker上启动应用程序,我使用-Dspring.profiles.active=docker运行,但是当应用程序启动时,会发生以下错误:

 Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private int com.inkdrop.config.cache.CacheConfiguration.redisPort; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type [java.lang.String] to required type [int]; nested exception is java.lang.NumberFormatException: For input string: "tcp://172.17.0.3:6379" 

出于某种原因,Spring Boot正在读取redis.porttcp://172.17.0.3:6379 。 所以对于testingbuild议,我从CacheConfiguration类中删除@Value注释,并手动将其设置为主机和6379作为端口,它的工作。 看起来像使用环境variables和@Value ,Spring会迷路。 任何人有一个想法?

基于Docker文档 :

撰写使用Docker链接将服务容器公开到另一个。 每个链接的容器都会注入一组环境variables, 每个环境variables都以容器的大写名称开始

Docker Compose将使用name_PORT格式创build一个表示容器完整URL的环境variables,例如REDIS_PORT=tcp://172.17.0.5:6379

并根据您docker-compose.yml文件:

 redis: image: tutum/redis ports: - "6379:6379" volumes: - /data 

你将得到一个名为REDIS_PORT的环境variables,其值等于tcp://172.17.0.3:6379 。由于OS环境variables相对于特定于configuration文件的应用程序属性具有更高的优先级,Spring Boot将通过redis.port REDIS_PORTredis.port ,所以错误:

由于:org.springframework.beans.factory.BeanCreationException:无法自动assembly字段:private int com.inkdrop.config.cache.CacheConfiguration.redisPort; 嵌套的exception是org.springframework.beans.TypeMismatchException:无法将[java.lang.String]types的值转换为所需的types[int]; 嵌套exception是java.lang.NumberFormatException:对于inputstring:“tcp://172.17.0.3:6379”

作为解决这个问题的一个解决方法,你应该用你的端口值来覆盖REDIS_PORT环境variables,或者把你的configuration名称从redis.name重命名为任何没有争议的东西。

有点话题,但只是从tutum-docker-redis引用Github存储库 :

这张图片即将被弃用。 请使用docker官方图片: https : //hub.docker.com/_/redis/