如何在Spring中从不同的包中使用Rest Controller?

huangapple go评论76阅读模式
英文:

How can I use a rest controller from a different package in Spring?

问题

发生了什么

我正在使用Java和Spring Boot。
我尝试创建一个简单的API。

我有一个名为Example的包。
我有两个子包,分别是configrest

config中有一个名为Application的类,它是我的Spring应用。
rest中有一个名为TheController的类,它是REST控制器。

目前,当我运行应用程序Application并尝试访问其中一个GET映射时,会出现白色标签错误页面。

然而,如果我将TheController移动到config包中,我就不会遇到这个错误,一切都很顺利。

我尝试过的方法

我尝试过使用导入语句。
com.Example.rest.*com.Example.rest.TheController,但没有结果。

非常感谢您的帮助 如何在Spring中从不同的包中使用Rest Controller?

英文:

What's going on

I am using Java, Springboot
I am trying to create a simple API.

I have a package called Example.
I have two sub-packages called config and rest.

In config is the class Application, which is my spring app.
In rest is the class TheController which is the rest controller

Currently when i run the app, Application and try and go to one of the get mappings i get a white label error page.

However if i move theController to the config package i do not get this error and it's plain sailing.

What I have tried

I have tried using an import statement.
com.Example.rest.* and com.Example.rest.TheControllerwith no results.

Any help would be appreciated 如何在Spring中从不同的包中使用Rest Controller?

答案1

得分: 2

在你的应用程序类上添加 @ComponentScan。

```java
package com.example.config;

@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class SpringBootComponentScanApp {

}

我个人认为将配置放在子包 "com.example.config" 而不是父包 "com.example" 中是一个好主意,但你需要覆盖Spring Boot的默认组件扫描方式。

参见 https://www.baeldung.com/spring-component-scanning


<details>
<summary>英文:</summary>

Add a @ComponentScan on your application class.

    package com.example.config;

    @SpringBootApplication
    @ComponentScan(basePackages = &quot;com.example&quot;)
    public class SpringBootComponentScanApp {

    }

I personally think it&#39;s a good idea to put your configuration in a sub-package &quot;com.example.config&quot; and not in the parent package &quot;com.example&quot;, but you need to override Spring Boot&#39;s default component scan for that case.

See also https://www.baeldung.com/spring-component-scanning

</details>



# 答案2
**得分**: 0

Spring Boot 只会从应用程序类的包(使用 `@SpringBootApplication` 注解)及其以下位置开始扫描组件(控制器、服务、存储库等)。

因此,最好使用 `com.example.Application`,然后您可以使用 `com.example.rest.TheController`,这样应该可以正常工作。

<details>
<summary>英文:</summary>

Spring Boot will only scan for components (controllers, services, repositories, ...) starting from the package of the application class (annotated with `@SpringBootApplication`) and below.

So best to use `com.example.Application`, then you can use `com.example.rest.TheController` and things should work.

</details>



huangapple
  • 本文由 发表于 2020年10月16日 18:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64387617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定