java - 使用像文件这样的自定义参数调用 Spring PropertySourcesPlaceholderConfigurer
问题描述
当我尝试运行我的 spring boot 项目时,我收到这样的错误:
描述:
AppConfig 中的方法 propertySourcesPlaceholderConfigurer 的参数 0 需要找不到类型为“java.io.File”的 bean。
行动:
Consider defining a bean of type 'java.io.File' in your configuration.
@SpringBootApplication
@Slf4j
public class AppRunner implements CommandLineRunner {
@Autowired
private BeanFactory beanFactory;
public static void main(String[] args) throws IOException {
SpringApplication.run(AppRunner.class, args);
}
@Override
public void run(String... args) throws Exception {
File file = new File("path\\credentials.properties");
PropertySourcesPlaceholderConfigurer report =
beanFactory.getBean(PropertySourcesPlaceholderConfigurer.class, file);
}
}
我的配置文件如下所示:
@Configuration
public class AppConfig {
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(File file) throws IOException {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setProperties(Utils.getProperties(file));
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true);
return propertySourcesPlaceholderConfigurer;
}
}
我想用参数调用单例bean。但是我尝试这样做,我得到了上面定义的错误。我该如何解决这个问题?
解决方案
您使用 PropertySourcesPlaceholderConfigurer 的目的是什么?您已经创建了 Bean,因此您可以通过 @Autowired 注入它。
带有@Bean 注解的方法在应用程序启动时通过 Spring 调用。如果要手动初始化该 bean,则必须删除 @Bean 注释或在 AppConfig 类中创建基于文件的 bean:
@Bean
public File getFile() {
return new File("path\\credentials.properties");
}
编辑:
如果您想在使用 @Bean 注释创建 bean 时使用命令行值,请查看这篇文章:Spring Boot:在 @Bean 注释方法中获取命令行参数
推荐阅读
- android - 错误:[Dagger/MissingBinding] *.AuthRepository 不能在没有 @Provides 注释的方法的情况下提供
- javascript - 动态创建提交输入类型
- spring - 在 Spring Cloud Gateway 故障转移期间保留请求的路径
- java - 如何解决 Spring 应用程序中的数据源错误?
- php - Laravel 8 安全(认为问题 datetime-local input field to mysql)
- jquery - 显示文本输入默认值
- apache-spark - 当您在表中开始或中间添加新列时,Impala 中的架构解析问题
- tailwind-css - 如何处理 Tailwind 和 PurgeCSS 以及很多不同的文件夹?
- flutter - Flutter:响应式定位在堆栈中
- html - HTML CSS 中元素之间的动态空间