Spring Boot 不加载 application.yml config

2022-09-04 04:54:06

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

@Configuration
    @EnableAutoConfiguration
    @ComponentScan(basePackages = "dreamteam.eho")
    @Import({EhoConfig.class})
    public class MainApp implements CommandLineRunner, ApplicationContextAware {

使用配置:

@Configuration
@EnableConfigurationProperties({RootProperties.class})
public class EhoConfig {
}

和属性:

@ConfigurationProperties("root")
public class RootProperties {
    private String name;

我尝试加载配置:

--spring.config.location=file:///E:/.../eho-bot/props/ --spring.profiles.active=eho

路径正确。但是yml没有加载;

application-eho.yml file:

logging:
  file: D:/java/projects/telegram-bots/eho.log
  level:
    dreamteam.eho: INFO
    org.springframework: DEBUG

root:
  name: EHO-BOT

应用使用 args 运行,但所有 props 为 null。未应用日志记录属性;sout:

--spring.config.location=file:///E:.../eho-bot/props/

--spring.profiles.active=eho

--spring.output.ansi.enabled=always

答案 1

此时此刻,您应该使用弹簧靴。

    @SpringBootApplication
    public class ReTestsApplication implements CommandLineRunner {

        public static void main(String[] args) {
            SpringApplication application = new SpringApplication(ReTestsApplication.class);
            application.setWebEnvironment(false);
            application.setBannerMode(Banner.Mode.OFF);
            application.run(args);
        }

        public void run(String... args) throws Exception {

        }
    }

使用 webEnvironmet=false 和 BannerMode=off(控制台应用程序)。

文档,请参阅 https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html#howto-externalize-configuration


答案 2

试试这个方式:

遵循应用程序结构,例如

App
└── src
|    ├── main
|         ├── java
|         │     └── <base-package>
|         │               └── Application.java (having public static void main() method)
|         │
|         ├── resources
|                ├─── application-eho.yml
|
├──── pom.xml

应用.java内容

@SpringBootApplication
@RestController
public class Application {

    public static void main(String[] args) {
        System.setProperty("spring.config.name", "application-eho");
        SpringApplication.run(Application.class, args);
    }

}

application-eho.yml file:

logging:
  file: D:/java/projects/telegram-bots/eho.log
  level:
    dreamteam.eho: INFO
    org.springframework: DEBUG

root:
  name: EHO-BOT

推荐