1.在没有任何构建工具的情况下,将java文件打包成classes后,把配置文件放在与class同级的目录下,spring 项目启动后默认到classes 顶层目录里找application.properties文件。

2.在有构建工具比如maven, gradle 的情况下,maven的Super POM配置将配置文件放在src/main/resources下,就可以不用告诉maven构建的时候要去哪里找到这个配置文件,而gradle支持maven,所以他们的约定是一样的,而打包完成后,application.properties也会被放到class的顶层文件夹内。

3.在没有构建工具但是有IDE的情况下,比如IDEA, 就手动告诉IDEA 配置文件在这里,操作步骤就是右击resources目录,将其mark 成Resource Root.

额外知识点:maven为什么会把打包后的文件都丢到yourproject/target/class下呢?这个配置在哪里?
打开IDEA的project structure, 可以看到project的output是到当前项目的/out目录,也不是/target。可以猜测这个配置肯定是被重写了

再打开pom.xml, 也没有outputDirectory的配置,那到底的配置哪里了呢?
<?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>org.springframework</groupId>
<artifactId>gs-actuator-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
于是打开了maven官方文档: https://maven.apache.org/guides/introduction/introduction-to-the-pom.html, 了解到Super POM,
Super POM
The Super POM is Maven's default POM. All POMs extend the Super POM unless explicitly set, meaning the configuration specified in the Super POM is inherited by the POMs you created for your projects. The snippet below is the Super POM for Maven 2.0.x.
也就是说,我们新建一个maven项目,写了项目的pom.xml, 当时执行的时候,用到的并不仅仅是我们写的pom.xml,而是我们的pom.xml会先去继承Super POM的配置,再执行。
那么这个target就是来自Super POM.: 从下面的配置可以看到,包括配置文件放哪里都已经写在Super POM里了。

当然这些属性都可以被修改, 通过修改自己项目里的pom.xml,比如我改写输出路径为target/other/classes:

然后在项目目录下执行(要打包后才能看到结果):$ ./mvnw clean package
再查看文件夹, classes信息已经被写入新的目录下了:

网友评论