首页 > 解决方案 > 使用像文件这样的自定义参数调用 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。但是我尝试这样做,我得到了上面定义的错误。我该如何解决这个问题?

标签: javaspringspring-boot

解决方案


您使用 PropertySourcesPlaceholderConfigurer 的目的是什么?您已经创建了 Bean,因此您可以通过 @Autowired 注入它。

带有@Bean 注解的方法在应用程序启动时通过 Spring 调用。如果要手动初始化该 bean,则必须删除 @Bean 注释或在 AppConfig 类中创建基于文件的 bean:

@Bean
public File getFile() {
    return new File("path\\credentials.properties");
}

编辑:

如果您想在使用 @Bean 注释创建 bean 时使用命令行值,请查看这篇文章:Spring Boot:在 @Bean 注释方法中获取命令行参数


推荐阅读