Springbootのクラスでは@Value注記を使用してymlから値をロードできません

1843 ワード

次のクラスでは@Valueを使用していますが、ymlから値を読み取ることはできません.どうすればいいですか?
@Valueタグクラスがあります.
package com.itmuch.cloud;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigClientController {

	@Value("${profile}")
	private String profile;

	@GetMapping("/profile")
	public String getProfile() {
		return this.profile;
	}
}

次のymlからProfileに対応する値を指定する必要があります.ymlは次のとおりです.
spring:
  cloud:
    config:
      uri: http://localhost:8080
      profile: dev
      label: master # ConfigServer     GIt   ,   master
  application:
    name: foobar
    

解決策:
上のクラスにこれを加える方法:
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
	   return new PropertySourcesPlaceholderConfigurer();
	}

@valueはymlから直接データを読み取ることができ、@Value(「${spring.cloud.config.profile}」)、直接@Value(「${profile}」)と書く必要はありません.
最後のクラスの完全なコードは次のとおりです.
package com.itmuch.cloud;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigClientController {

	@Value("${profile}")
	private String profile;

	@GetMapping("/profile")
	public String getProfile() {
		return this.profile;
	}
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
	   return new PropertySourcesPlaceholderConfigurer();
	}


}