在spring 5中,我想在Autowired中使用泛型。例如,我认为我有utill类,并且在类中有将StudentDTO转换为StudentEntity的方法,反之亦然。
@Component
public class Convert<T,U> {
public <T,U> U convertEntityAndDTO(T t, U u){
BeanUtils.copyProperties(t,u);
return u;
}
}现在我想把它注入到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());发布于 2020-04-13 04:23:32
我认为您正在寻找一个完全泛化类的两个实例,对吗?
首先,您需要bean的两个实例,这样@Component就不会工作,因为它只创建一个实例。相反,您需要一个带@Configuration注释的类,您可以在其中定义两个带@Bean注释的方法,返回适当泛化的类型。
现在,由于类型擦除,您不能只声明预期泛化类型和@Autowired注释的两个属性,因为自动装配是按类型进行的,因此在运行时这两个bean是相同的类型。相反,您可以按名称自动布线-比方说,一个bean定义在名为fromDtoConverter()的方法中,另一个定义在名为toDtoConverter()的方法中,然后在泛化属性上使用@Resource("fromDtoConverter")和@Resource("toDtoConverter")而不是@Autowired。
发布于 2020-05-22 20:44:58
从Spring4开始,你就可以自动连接泛型了。问题是您没有告诉您的服务要注入哪种类型的Convert。尝试在您的服务中添加@Autowire上的类型:
@Service
public class StudentService {
@Autowired
Convert<Student, StudentDTO> convert;
public StudentDTO getStudent(Integer id) {
Student student = studentRepository.getStudent(id);
Object o = convert.convertEntityAndDTo(student, new StudentDTO());
return (StudentDTO) o;
}
}https://stackoverflow.com/questions/61177313
复制相似问题