当我缺少软件包中的最后一个目录时,为什么要编译它?

时间:2018-08-21 09:31:21

标签: java spring maven spring-boot

当我缺少软件包中的最后一个目录时,为什么要编译并运行它?

最近几天我正在学习springboot。当我运行代码时,它将编译并可以在浏览器中进行访问。但是,我发现我的包路径没有完全写完。

enter image description here

如您所见,package必须为com.test.forfree.controller,但在我的代码中为com.test.forfree

package com.test.forfree;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Hello Boot 2.10!";
    }
}

我使用mvn spring-boot:run运行此项目,它的工作原理是:

enter image description here

然后将package语句更改为com.test.forfree.controller

package com.test.forfree.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Hello Boot 2.10!";
    }
}

它仍然可以成功编译并运行。为什么?

1 个答案:

答案 0 :(得分:1)

目录和程序包名称的对齐通常是源代码的一个好主意,但并非严格要求。工具可能会抱怨代码,警告您并仍然对其进行编译,或者只是静默地编译您的代码,具体取决于您对代码进行编译的方式。

目录结构必须与包结构相匹配的位置是用于类文件(直接在jar文件中的磁盘上)。

如果检查target目录的内容,您会注意到.class文件都在“正确”目录中,即使原始源文件不在。