Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从外部库使用NewInstance创建的Autowire Java Bean_Java_Spring_Spring Boot_Spring Mvc_Opencsv - Fatal编程技术网

从外部库使用NewInstance创建的Autowire Java Bean

从外部库使用NewInstance创建的Autowire Java Bean,java,spring,spring-boot,spring-mvc,opencsv,Java,Spring,Spring Boot,Spring Mvc,Opencsv,我正在做一个Spring引导项目,并使用OpenCSV库将一些CSV解析为POJO,以持久化到db OpenCSV使用注释@CsvCustomBindByName将CSV字段映射到Java对象 converter=DepartmentConverter.class是一个自定义转换器,通过以下方式实例化: Class<? extends AbstractBeanField<T,K>>.newInstance() 在我的DepartmentConverter中,我需要使用

我正在做一个Spring引导项目,并使用OpenCSV库将一些CSV解析为POJO,以持久化到db

OpenCSV使用注释
@CsvCustomBindByName
将CSV字段映射到Java对象

converter=DepartmentConverter.class
是一个自定义转换器,通过以下方式实例化:

Class<? extends AbstractBeanField<T,K>>.newInstance() 
在我的DepartmentConverter中,我需要使用SpringJParepository来检索一些数据。无法自动连接DepartmentRepository

    @Component
public class DepartmentConverter extends AbstractBeanField<Department, String> {

    @Autowired
    private DepartmentRepository departmentRepository;

    public DepartmentConverter() {

    }

    @Override protected Object convert(String val) throws CsvConstraintViolationException, ResourceNotFoundException {
        //use departmentRepository
        ...
    }
}
@组件
公共类DepartmentConverter扩展AbstractBeanField{
@自动连线
私人部门储存库部门储存库;
公共部门转换器(){
}
@重写受保护对象转换(字符串val)引发CsvConstraintViolationException、ResourceNotFoundException{
//使用部门存储库
...
}
}
您所指的
newInstance()
调用位于
HeaderColumnNameMappingStrategy
类中,该类调用
InstanceCustomConverter()
方法来执行
newInstance()
调用

创建子类并重写该方法:

@覆盖

受保护的BeanField实例化eCustomConverter(类否则您如何获得该实例?也许您可以创建@Bean方法将其添加到上下文中?就是这样!非常感谢!)
    @Component
public class DepartmentConverter extends AbstractBeanField<Department, String> {

    @Autowired
    private DepartmentRepository departmentRepository;

    public DepartmentConverter() {

    }

    @Override protected Object convert(String val) throws CsvConstraintViolationException, ResourceNotFoundException {
        //use departmentRepository
        ...
    }
}