java - 如何在 SpringBoot 中配置 YML 文件?
问题描述
我正在尝试配置我的 .yml 但我总是得到一个空指针异常......
我有以下.yml:
search_files:
csv:
path: ./
name: export_files_
extension: .csv
我有以下pom配置:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dspring.config.location=file:${home}/config/application.yml</argLine>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/application.yml</exclude>
</excludes>
</resource>
</resources>
</build>
而我的实现:
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.victorprojects.utils.searchFiles.entity.bean.Result;
@Component
public class CSVUtils {
@Value("${search_files.csv.path}")
private static String PATH;
@Value("${search_files.csv.name}")
private static String NAME;
@Value("${search_files.csv.extension}")
private static String EXTENSION;
public void createCsv(ArrayList<Result> results) {
try {
String fullPath = PATH.concat(NAME.concat(getCurrentDateTime().concat(EXTENSION)));
FileWriter fileWriter = new FileWriter(fullPath, true);
CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.RFC4180);
// HEADER
csvPrinter.printRecord("Name", "Extension", "Size (Kb)", "Path");
for (Result result : results) {
// DATA
csvPrinter.printRecord(result.getName(), result.getExtension(), result.getSize(), result.getPath());
}
csvPrinter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当我执行它时,我收到以下消息:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.springframework.core.env.Environment.getProperty(String)" because "this.env" is null
at com.victorprojects.utils.searchFiles.utils.CSVUtils.createCsv(CSVUtils.java:28)
我在互联网上搜索了很多信息,但我总是得到同样的错误......
我该如何解决这个问题?
编辑
我添加了一张关于我的项目结构的照片:
你可以在这里下载项目:
解决方案
I have solved my problem... I was initializing the CSVUtils constructor like this:
Utils utils = new Utils();
But I needed to initialize it this way:
@Autowired
Utils utils;
With the first way, I was initializing explicity the constructor, but I needed to do that with the Spring annotation to be able to use @Value
.