java Spring YML数组属性为空
我试图从application.yml
读取字符串数组,但徒劳。
Environment
和@Value
注释始终返回null
如果我读取一个项目,而不是整个数组,那么一切都会正常工作
代码如下:
来源
启动应用程序和Rest控制器
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
class WithEnvCtrl {
@Autowired
private Environment env;
@RequestMapping(value = "/with_env", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json")
public String test() {
System.err.println(env.getProperty("this.is.array[0]"));
System.err.println(env.getProperty("this.is.array", List.class));
System.err.println(env.getProperty("this.is.array", String[].class));
return env.getProperty("this.is.array[0]");
}
}
@RestController
class WithValueAnnotation {
@Value("${this.is.array[0]}")
private String first;
@Value("${this.is.array}")
private List<String> list;
@Value("${this.is.array}")
private String[] array;
@RequestMapping(value = "/with_value_annotation", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json")
public String test() {
System.err.println(first);
System.err.println(list);
System.err.println(array);
return first;
}
}
应用程序。yml文件
this:
is:
array:
- "casa"
- "pesenna"
结果
WithEnvCtrl.test
方法打印:
casa
null
null
null
WithValueAnnotation.test
方法使用数组的第一个元素(casa
)正确设置变量first
。但是,属性list
和array
上的注释@Value
会导致异常:
java.lang.IllegalArgumentException: Could not resolve placeholder 'this.is.array' in string value "${this.is.array}"
下面是一个示例项目:property-array
非常感谢
# 1 楼答案
解决者:
@ConfigurationProperties
李>代码如下:
谢谢@Quagaar