gpt4 book ai didi

spring-boot - Spring Boot 不加载 application.yml 配置或?

转载 作者:行者123 更新时间:2023-12-04 03:17:18 24 4
gpt4 key购买 nike

我有一个简单的主应用程序:

// Application.java
package com.my.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.my")
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}

只是一个类:
// TestClass.java
package com.my.application;

public class TestClass
{
public TestClass()
{

}
}

使用配置:
//ApplicationConfiguration
package com.my.configuration;

import com.my.application.TestClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class ApplicationConfiguration
{
@Autowired
Environment env;

@Bean TestClass getTestClass()
{
System.out.println(env.getProperty("test"));

return new TestClass();
}
}

这是我的 pom 文件:
// 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.my</groupId>
<artifactId>test</artifactId>
<version>1.3.0</version>
<packaging>pom</packaging>
<name>test</name>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
</dependencies>

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

</project>

application.yml 文件只是:
// src/main/resources/application.yml

test: 123

属性“测试”始终 = null。
我做错了什么?
尝试使用@Value,@ConfigurationProperties,
@EnableConfigurationProperties,
@PropertySource("classpath:src/main/resources/application.yml") 注释,
没有snakeyaml库,
使用另一个 spring-boot 版本,
但结果总是一样的。

最佳答案

这与 Maven 有关 - application.properties当您使用 <packaging>pom</packaging> 时,它不是构建的一部分在您的 pom 文件中 - 因此当您启动应用程序时,该文件不在那里可供读取。

删除 <packaging>pom</packaging>从你的 pom 开始,你应该很高兴。

关于spring-boot - Spring Boot 不加载 application.yml 配置或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54839765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com