Application.yml参数注入到数组
跳到导航
跳到搜索
首先,因为 @Value 的实现机制,下面这种注入是不支持的
application.yml
include:
- E:\record\2022
- E:\record\2023
Application.java
@SpringBootApplication
@Slf4j
@Data
public class Application implements CommandLineRunner {
@Value("${include}")
String[] include;
public static void main(String[] args) {
log.info("STARTING THE APPLICATION");
SpringApplication.run(Application.class, args);
log.info("APPLICATION FINISHED");
}
@Override
public void run(String... args) {
for (String str:include) {
log.info(str);
}
}
}
会报错:
……
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'include' in value "${include}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.3.1.jar:5.3.1]
……
可以作为对象的属性注入
application.yml
args:
include:
- E:\record\2022
- E:\record\2023
Args.java
@Component
@ConfigurationProperties(prefix="args")
@Data
public class Args {
private String[] include;
}
Application.java
@SpringBootApplication
@Slf4j
@Data
public class Application implements CommandLineRunner {
@Autowired
Args args;
public static void main(String[] args) {
log.info("STARTING THE APPLICATION");
SpringApplication.run(Application.class, args);
log.info("APPLICATION FINISHED");
}
@Override
public void run(String... args) {
log.info("EXECUTING : command line runner");
for (String str:this.args.getInclude()) {
log.info(str);
}
}
}