在 spring 5 中,我想在 Autowired 中使用 Generic。 例如,我认为我有 utill 类,并且在类中有将 StudentDTO 转换为 StudentEntity 的方法,反之亦然。
@Component
public class Convert<T,U> {
public <T,U> U convertEntityAndDTO(T t, U u){
BeanUtils.copyProperties(t,u);
return u;
}
}
现在我想将它注入(inject) SudentService 类并使用它们
public class StudentService {
@Autowired
Convert convert;
//I need both of them in class
//convert<Student,StudentDTO> convert
//convert<StudentDTO,Student> convert
public StudentDTO getStudent(Integer id){
Student student = studentRepository.getStudent(id);
Object o = convert.convertEntityAndDTo(student, new StudentDTO());
return (StudentDTO)o;
}
我可以使用向下转型,但不能使用通用
convertEntityAndDTo(student, new StudentDTO());
convertEntityAndDTo(studentDTO, new Student());
最佳答案
我认为您正在寻找完全泛型类的两个实例,对吗?
首先,您需要 bean 的两个实例,因此 @Component
将无法工作,因为它会创建单个实例。相反,您需要一个 @Configuration
注解的类,您可以在其中定义两个 @Bean
注解的方法,返回适当的泛型类型。
现在,由于类型删除,您不能只声明预期泛型类型和 @Autowired 注释的两个属性,因为 Autowiring 是按类型进行的,因此在运行时两个 bean 是相同的类型。相反,您可以按名称 Autowiring - 假设一个 bean 在名为 fromDtoConverter()
的方法中定义,另一个 bean 在名为 toDtoConverter()
的方法中定义,然后代替 @ Autowired
在通用属性上使用 @Resource("fromDtoConverter")
和 @Resource("toDtoConverter")
。
关于java - spring 5 中 Autowiring 的通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61177313/