目录
一、解决方案
在项目的pom.xml中添加以下依赖,添加依赖后记得要刷新maven重新加载依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
二、原因分析
一般该问题常见搭建springcloud新项目,如果在原有项目中集成了nacos或者eruak,在其依赖中已经包含了spring-cloud-context,所以可以配置可以生效。
以nacos为例,maven配置依赖图如下:
图中可以看到,我们添加了nacos的如下配置后,会自动添加spring-cloud-context的依赖
<!--配置中心客户端 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
三、项目演示
在没有添加spring-cloud-context依赖时,在bootstrap.properties只配置应用端口号:
server.port=6001
启动项目:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.7.RELEASE)
2022-07-22 09:47:26.537 INFO 4699 --- [ main] com.zhufeng.web.MsgApplication : Starting MsgApplication on MacBook-Pro-lichao.local with PID 4699 (/Users/lichao/soft/workplace-idea/gitee/zhufeng-cloud/zhufeng-web/zhufeng-web-msg/target/classes started by lichao in /Users/lichao/soft/workplace-idea/gitee/zhufeng-cloud)
2022-07-22 09:47:26.538 INFO 4699 --- [ main] com.zhufeng.web.MsgApplication : No active profile set, falling back to default profiles: default
2022-07-22 09:47:26.852 INFO 4699 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
启动日志中可以看到 Tomcat initialized with port(s): 8080 (http)
也就是自定义的端口并没有生效,添加spring-cloud-context依赖后重新启动
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.7.RELEASE)
2022-07-22 09:50:52.526 INFO 4744 --- [ main] com.zhufeng.web.MsgApplication : No active profile set, falling back to default profiles: default
2022-07-22 09:50:52.711 INFO 4744 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=eff494ba-68ba-365b-9df0-a3cd776b9c8c
2022-07-22 09:50:52.781 INFO 4744 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 6001 (http)
此时启动日志中可以看到端口号变为6001 Tomcat initialized with port(s): 6001 (http)