🗒️

springboot/springcloud 学习/踩坑笔记

2024-02-293 分钟1,028

目录

type
Post
status
Published
date
Feb 1, 2024
slug
spring-difficult
summary
tags
开发
category
技术分享
icon
password

1.springboot 怎么在application访问指定文件夹(controller)文件夹中的资源

在 Spring Boot 应用程序中,如果你希望在 application 中访问 controller 文件夹中的资源(如其他 Controller 或类),通常可以使用 @ComponentScan 注解来扫描包路径,以确保 Spring 能够找到并注册这些资源。

使用 @ComponentScan 扫描 Controller 文件夹中的资源:

假设你的 Controller 文件夹中包含了一些其他的 Controller 类,可以按照以下步骤在 application 中访问这些资源:
  1. @ComponentScan 注解添加到你的主应用程序类上:
    1. @ComponentScan 注解中,将 controller 替换为你的 Controller 类所在的包路径。这样 Spring 就会扫描并注册该路径下的所有 @RestController@Controller 注解的类。
  1. 确保 Controller 类上添加了 @RestController@Controller 注解:
    1. 确保你的 Controller 类上有正确的注解,并且定义了相应的映射路径。
通过这种方式,在 application 中访问 controller 文件夹中的资源时,Spring Boot 应该能够识别和注册这些资源,使其在应用程序中可用。

2.指定项目的启动端口

Spring Boot 整个应用程序只有一个配置文件,那就是 .properties 或 .yml 文件。但是,在前面的示例代码中,我们并没有看到该配置文件,那是因为 Spring Boot 对每个配置项都有默认值。当然,我们也可以添加配置文件,用以覆盖其默认值,这里以 .properties 文件为例,首先在 resources 下新建一个名为 application.properties(注意:文件名必须是 application)的文件,键入内容为:
并且启动 main 方法,这时程序请求地址则变成了:http://localhost:8081/api/hello。
Spring Boot 支持 properties 和 yaml 两种格式的文件,文件名分别对应 application.properties 和 application.yml,下面贴出 yaml 文件格式供大家参考:
可以看出 properties 是以逗号隔开,而 yaml 则换行+ tab 隔开,这里需要注意的是冒号后面必须空格,否则会报错。yaml 文件格式更清晰,更易读,

冷苏

全栈开发者 · 前端 / 移动端 / Python / 桌面应用

GitHub ⟶

1.0k

字数

3

分钟