Java 其他包中的@RestController 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33039774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:13:07  来源:igfitidea点击:

@RestController in other package doesn't work

javaspringmavenpackagespring-restcontroller

提问by CeZet

I start with learning Spring and I create basic project which creates database, insert values and next print it in web browser. My problem is that when I have RestController in the same package like main class - its OK, but I want distribute it to other package and when I create new package, move the RestController it doesn't work. Let met explain:

我从学习 Spring 开始,创建了创建数据库、插入值然后在 Web 浏览器中打印的基本项目。我的问题是,当我将 RestController 放在与主类相同的包中时 - 没关系,但我想将它分发到其他包,当我创建新包时,移动 RestController 它不起作用。让见面解释:

My project looks like:

我的项目看起来像:

          |-Springtestv_01
            |-src/main/java
              |--com.person <-- it's a main package
                 |-Main.java
                 |-Person.java
                 |-PersonLineRunner.java
                 |-PersonRepository.java
                 |-PersonController.java
              |-com.controller <-- second package, I want put here PersonController.java
            |-src/main/resources
              |-data.sql
            pom.xml

My controller looks:

我的控制器看起来:

@RestController
public class PersonController {

    @Autowired PersonRepository personRepository;

    @RequestMapping("/persons")
    Collection<Person> persons(){
        return this.personRepository.findAll();
    }
}  

When everything is in com.personpackage, I write in web brower http://localhost:8080/personsand it works correctly... But I Want move PersonController.javato com.controllerpackage, and when I moved it, my webbrowers calls me

当一切都在com.person包,我写的网络浏览器的http://本地主机:8080 /人,它正常工作......但我想移动PersonController.javacom.controller包,当我把它,我webbrowers打电话给我

There was an unexpected error (type=Not Found, status=404). No message available

出现意外错误(类型=未找到,状态=404)。没有可用的消息

and I have no idea what I should do to repair it. Maybe I should change something in my pom.xml??

我不知道我应该怎么做才能修复它。也许我应该在我的pom.xml??

My pom.xml looks like

我的 pom.xml 看起来像

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.person</groupId>
    <artifactId>person</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringTest_v0_1</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.BUILD-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.h2database</groupId><artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>
                spring-boot-starter-data-elasticsearch
            </artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

It is generated automatically, I write only one dependency

是自动生成的,我只写了一个依赖

    <dependency>
        <groupId>com.h2database</groupId><artifactId>h2</artifactId>
    </dependency>

采纳答案by question_maven_com

Use basePackages:

使用基本包:

@ComponentScan(basePackages = { "com.person","com.controller"} )

回答by spm

Using a @SpringBootApplicationannotation is equivalent to using @Configuration, @EnableAutoConfigurationand @ComponentScan.

使用@SpringBootApplication注解等同于使用@Configuration,@EnableAutoConfiguration@ComponentScan

From the documentation:

从文档:

ComponentScan configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's element.

One of basePackageClasses(), basePackages() or its alias value() may be specified to define specific packages to scan. If specific packages are not defined scanning will occur from the package of the class with this annotation.

ComponentScan 配置用于@Configuration 类的组件扫描指令。提供与 Spring XML 元素并行的支持。

可以指定 basePackageClasses()、basePackages() 或其别名 value() 之一来定义要扫描的特定包。如果未定义特定包,将从带有此注释的类的包中进行扫描。

You can either move it as you did or specify basePackagesin @ComponentScan.

您可以按原样移动它,也可以basePackages@ComponentScan.

回答by Adimax

We can use @ComponentScan (basePackages = {"include your package name here"}).

我们可以使用@ComponentScan (basePackages = {"include your package name here"}).

Also if you have some common package naming format, then we can include just common part of package name with *like @ComponentScan(basePackages = { "com.*"}, so that all packages having that common package name will get scanned.

此外,如果您有一些通用的包命名格式,那么我们可以只包含包名的公共部分,以便使用*like @ComponentScan(basePackages = { "com.*"},以便扫描所有具有该通用包名的包。

回答by DevRj

I had the same problem the answers provided here worked for me but i had to add another spring annotation and it's more general in case dealing with a lot of repositories. We have the following structure :

我遇到了同样的问题,这里提供的答案对我有用,但我不得不添加另一个 spring 注释,并且在处理大量存储库的情况下它更通用。我们有以下结构:

 |-src/main/java
    |--com.person 
       |--repositories
       |--controllers
       |--...

This then should be added in th main

这然后应该添加到 th main

@SpringBootApplication(scanBasePackages = {"com.person"}) 
@EnableMongoRepositories(basePackages = "com.person.repositories")
public class MainDemoApplication { //
}

回答by Denys

I had the same problem but suddenly found that my Application.java class (the class with main method and @SpringBootApplication annotation) located in different but parallel package with @Controller class.

我遇到了同样的问题,但突然发现我的 Application.java 类(带有 main 方法和 @SpringBootApplication 注释的类)与 @Controller 类位于不同但并行的包中。

The thing is that Application.java class should be in same or on top of all other packages, then we don't need any @ComponentScan and all beans will be scanned automatically. For example: if Application.java located in com.person and all application beans located in com.person, then it will work without @ComponentScan.

问题是 Application.java 类应该在所有其他包中或在所有其他包之上,然后我们不需要任何 @ComponentScan 并且所有 bean 将被自动扫描。例如:如果 Application.java 位于 com.person 并且所有应用程序 bean 位于 com.person,那么它会在没有@ComponentScan 的情况下工作。

回答by Eugene

As the one who has struggled with the issue, if you found provided solution didn't work.
Please check whether you put source files at the root level directly, for instance,
src\main\java\xxx.java

作为一直在努力解决问题的人,如果您发现提供的解决方案不起作用。
请检查您是否直接将源文件放在根级别,例如,
src\main\java\xxx.java

It has negative effect to project but I don't know the root cause. Anyway,

它对项目有负面影响,但我不知道根本原因。反正,

Please put source files to at least a self-created package like: src\main\java\pack1\xxx.java

请将源文件至少放在一个自创建的包中,例如: src\main\java\pack1\xxx.java

Try other settings again. It did solve my problem.

再次尝试其他设置。它确实解决了我的问题。

回答by Geet Thakur

You just only define a package name in @ComponentScanlike :

您只需在@ComponentScan 中定义一个包名称, 例如:

@SpringBootApplication
@ComponentScan({"com.project.pck_name"})
public class MainClassHome {

    public static void main(String[] args) {
        SpringApplication.run(MainClassHome.class, args);
    }
}

and update project after that:- right click on Your project -> maven -> update project

然后更新项目:-右键单击您的项目-> Maven -> 更新项目

回答by Akash

Instead of using ComponentsScan, we can use @Import.

我们可以使用 @Import 代替 ComponentsScan。

@Configuration

@Import({PersonController.class})

public class MainClassHome {

    public static void main(String[] args) {
        SpringApplication.run(MainClassHome.class, args);
    }
}

回答by Shirantha Madusanka

Assuming the main method is in the package called com.setech.app and a controller is in a package called com.setech.controller.

假设 main 方法位于名为 com.setech.app 的包中,控制器位于名为 com.setech.controller 的包中。

For spring-boot 1.3.x upwards try this by adding "scanBasePackages" like this.

对于 spring-boot 1.3.x 以上的版本,可以通过添加这样的“scanBasePackages”来尝试。

@SpringBootApplication(scanBasePackages = { "com.setech"} )
public class ResttanslatorApplication {

    public static void main(String[] args) {

        SpringApplication.run(ResttanslatorApplication.class, args);
    }

}

}

Credit goes to Kamil Wozniak from here.

功劳归于 Kamil Wozniak 从这里

回答by andy65007

For Maven Case: if you put the controller in another different sub-module(not same as main class), you should add dependency in pom.xml.

对于 Maven 案例:如果将控制器放在另一个不同的子模块中(与主类不同),则应在 pom.xml 中添加依赖项。