无法使用路径映射控制器

时间:2019-06-18 09:02:30

标签: java spring spring-boot

我有一个没有任何bean或持久性的简单Java Spring Boot项目。我创建了多个程序包以按功能分开类。

我读到控制器必须在初始包NameApplication.java中。但是,我在端口8080上启动了项目,并将下一个URL localhost:8080 / hello / grettings显示给我 Whitelabel错误页面,但我将localhost:8080并加载了index.html

为什么不起作用?

@Controller
@RequestMapping("/hello")
public class BasicController {

    @GetMapping(path = {"/grettings", "/helloworld"})
    public String grettings() {
        return "index";
    }
}

application.properties

# Application name.
spring.application.name=CursoSpring 

# Logging
logging.level.root=WARN
logging.level.com.globalomnium=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

#Flyway
#spring.flyway.baseline-on-migrate=true

# THYMELEAF
#spring.thymeleaf.check-template-location=true
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML
#spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.servlet.content-type=text/html 
spring.thymeleaf.cache=false


# Server HTTP port.
server.port=8080

pom.xml

<dependencies>
    <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-thymeleaf</artifactId> 
    </dependency>

</dependencies>

包装结构

enter image description here

2 个答案:

答案 0 :(得分:4)

CursoSpringApplication是应用程序的起点。启动时,它将搜索诸如@ Controller,@ Service,@ Repository和@Component之类的组件。通常建议您将主应用程序类放在其他类之上的根包中。因此,应将此CursoSpringApplication类放置在大多数外部包中。将com.globalomnium.axis.maps更改为com.globalomnium.axis

示例结构

com
 +- example
     +- myapplication
         +- Application.java
         |
         +- customer
         |   +- Customer.java
         |   +- CustomerController.java
         |   +- CustomerService.java
         |   +- CustomerRepository.java
         |
         +- order
             +- Order.java
             +- OrderController.java
             +- OrderService.java
             +- OrderRepository.java

read more

答案 1 :(得分:1)

我建议您通过更改void main来检查Controller Bean是否正在加载:

  public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(CursoSpringApplication.class, args);

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }

您应该看到控制台中列出了bean“基本控制器”。 我还将CursoSpringApplication放置在基本包“ com.globalomnium”而不是“ com.globalomnium.axis.maps”中,以便spring可以处理基本包下方的所有带注释的bean。

希望有帮助