【问题标题】:spring boot can not get configuration from application.ymlspring boot 无法从 application.yml 获取配置
【发布时间】:2019-05-19 10:45:13
【问题描述】:

我的 Spring Boot 应用程序无法从 application.yml 文件中获取配置参数。我的主要课程如下:

@SpringBootApplication(scanBasePackages={"com.test"})
public class Main {
    @Bean
    public Validator validator(){
        return new  org.springframework.validation.beanvalidation.CustomValidatorBean();
    }
    public static void main(String[] args) throws IOException {
        new SpringApplicationBuilder(Main.class)
        .properties("application.yml")
        .build()
        .run(args);
    }
}

我的控制器类如下:

@RestController
@RequestMapping("/test_traffic")
@Component
public class AnycastTrafficController {
    @Autowired
    TestService testService;

    @GetMapping("/test")
    public Object component() {
         return testService.getTraffic();
    }
}

我的服务类如下:

@Service
public class TestService {
    @Autowired
    TestDao testDao;

    public Object getTraffic() {
        testDao.getTraff();
    }
}

我的道类如下:

@Component
public class TestDao {

    @Autowired
    MyDBConfig mydbConfig;

    public DB getMyDBConfig () {
        DB db = new DB(mydbConfig.id, mydbConfig.key);
        return db;
    }
}

我的配置类如下:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "mydb")
public class MyDBConfig {

    public String id;
    public String key;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
}

我的 application.yml(位于 /src/main/resources)如下:

server:
  port: 8003
  context-path: /

logging:
  level:
    ROOT: INFO
    org.springframework: INFO
    org.springframework.data: INFO
    com.alibaba: INFO
  file: log/

docserver:
  accessKeyId: 1111
  accessKeySecret: 2222

---

spring:
  profiles: dev
  application:
    name: test-application
mydb:
  id: 1111111
  key: 2222222

但是当我启动 Main 类并请求 url 时,它抛出了如下异常:

the id should not be empty.

这意味着我的配置类没有从 yml 文件中获取配置数据,所以请问我哪里做错了。 p.s(但应用程序可以找到服务器端口 8003)。谢谢!

【问题讨论】:

  • application.yml 文件在哪里?如果它在资源目录(src/main/resources)中,spring boot 应该会自动找到它,而不必指定它。
  • 是的,它位于/src/main/resources,可以找到服务器8003端口,但是无法读取mydb数据。
  • 当我评论你在应用程序中的所有内容并且我只保留 mydb 和子属性时它可以工作!
  • 您是否在设置活动配置文件?如果没有,Spring 将不会默认为 dev 并将忽略该部分 stackoverflow.com/questions/37700352/…

标签: spring spring-boot


【解决方案1】:

您的 application.yml 包含无效的属性选项。

代替

spring:
  profiles: dev

你应该使用

spring:
  profiles:
    active: dev

更正此问题后,配置处理器应该可以正常工作。

【讨论】:

  • 另外 server.context-path 已被标记为已弃用,请改用 server.servlet.context-path。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 2018-03-24
  • 2018-09-24
  • 2018-08-10
  • 2019-11-23
  • 2022-01-23
  • 2019-07-17
相关资源
最近更新 更多