-1

I have encountered with the following issue. I would like to create Spring @Component with generic

@Component
public class ResponseDtoValidator<DTO> {

public ResponseEntity<DTO> methodToInvoke(DTO dto) {
return Optional.ofNullable(dto).map(result -> new >ResponseEntity<>
(result, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
}

@Controller
public class SomeController {
@Inject
private ResponseDtoValidator<DTO1> responseDtoValidator1;

@Inject
private ResponseDtoValidator<DTO2> responseDtoValidator2;

public void someMethod() {
DTO1 dto1 = new DTO1();
DTO2 dto2 = new DTO2();
responseDtoValidator1.methodToInvoke(dto1);
responseDtoValidator2.methodToInvoke(dto2);
}
}

Can I inject this Component like above? Actually, I have tried and it seems to work properly, can you please confirm that I am correct or not?

Igor Orekhov
  • 107
  • 7

1 Answers1

0

Firstly, a spring bean can not be injected in itself.

In regards to your question,yes it is injectable but dont use generic signs when injecting. Just inject it normally. Generic type is send when a method of generic class is utilizing.

For instance;

@Component 
public class ResponseDtoValidator<DTO> {

    public void getAbc(List<DTO> aList) {}
}

Then;

public class Test {

    @Autowired // or @Inject
    private ResponseDtoValidator responseDtoValidator;

    public void testMethod() {
        responseDtoValidator.getAbc(List<EnterATypeInHere> aList);
    }
}
Gökhan Polat
  • 431
  • 4
  • 9
  • Please, read this article: https://blog.jayway.com/2013/11/03/spring-and-autowiring-of-generic-types/ – Igor Orekhov Jul 28 '17 at 12:47
  • It is same what i wrote @IgorOrekhov – Gökhan Polat Jul 28 '17 at 12:56
  • Oh, I have understood what you meant. But what the reason why I should not use generic signs when injecting? It is just useless due to the fact that generic type is sent only on method invocation? – Igor Orekhov Jul 28 '17 at 13:03
  • When a bean is injected it means that Spring creates a class of the component, in my case the bean created as singleton. In case with @Component with generic, generic type must be defined when creating the bean. What if I send various DTO-s to this one injected bean, how will he able to handle it? – Igor Orekhov Jul 28 '17 at 13:24
  • If you give generic type when creating bean, you can not use the bean with another object. For instance ; `@Inject ResponseDtoValidator responseDtoValidator;` You can use this bean only to send to `Type1Object` parameter. If you write like this: `responseDtoValidator.getAbc(List aList);` it get incompatible argument type error. – Gökhan Polat Jul 29 '17 at 09:58