请帮助在 Sprint Boot 中访问 yaml 文件中的值。我收到如下错误。我可以访问 AppConfig 类中 filepath1 变量的值,但不确定为什么会出现错误。
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'filepath1' in value "${filepath1}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
我的主类如下
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args)
{
System.out.println("Starting ");
SpringApplication.run(DemoApplication.class, args);
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApplication.class);
Employee employee = applicationContext.getBean(Employee.class);
System.out.println("Exiting ");
}
}
配置类如下
@Slf4j
@Configuration
@ComponentScan("com.vish.springbootdemo.demo")
public class AppConfig
{
@Value("${filepath1}")
private String file1;
@Bean
public Employee employee()
{
System.out.println("file1 is " + file1);
return new Employee();
}
}
这是 application.yml
filepath1: "vish"
答案 0 :(得分:0)
像这样启动你的 Spring Boot 应用程序:
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
Resources 文件夹应该包含 application.yml。
filepath1: vish
用@Autowired 注入你的 bean
@Component
class AnotherComponent {
@Autowired Employee employee;
}
答案 1 :(得分:0)
问题在于,在 main
方法中,您正在创建自己的应用程序上下文:
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(DemoApplication.class);
这将与 Spring Boot 为您创建的应用程序上下文完全分离,并且其中不会包含来自 application.yml
的配置属性。
不要这样做,而是使用 Spring Boot 提供的应用程序上下文。更好的是:不要在应用程序上下文中显式查找 bean,而是让 Spring Boot 为您自动装配 bean。
像这样:
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private Employee employee;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("Employee: " + employee);
}
}
应用配置:
@Configuration
public class AppConfig {
@Value("${filepath1}")
private String file1;
@Bean
public Employee employee() {
System.out.println("file1 is " + file1);
return new Employee();
}
}