我是 Spring 新手,我正在尝试弄清楚如何在我的 Spring Boot 应用程序中使用环境变量。
当我运行 JAR 时,我收到以下消息:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field fooConfig in com.example.controller.HomeController required a bean of type 'com.example.config.FooConfig' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.config.FooConfig' in your configuration.
我完全不确定我是否正确使用了注释,或者它正在为我的配置 POJO 扫描正确的路径。我希望我可以运行具有更详细输出的 JAR 以查看此信息,但我不知道这是否可行或如何执行此操作。
我有以下类定义:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages={"com.example.controller"})
@ConfigurationPropertiesScan("com.example.config")
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
package com.example.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@Configuration
@ConfigurationProperties(prefix = "foo")
public class FooConfig {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
package com.example.controller;
import com.example.config.FooConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@Autowired
public FooConfig fooConfig;
@GetMapping("/")
public String index() {
System.out.println(fooConfig.getBar());
return new FooConfig().getBar();
}
}
在我的application.properties
档案中,
foo.bar=HelloWorld