Dependency Injection - Two objects implementing the same interface

Asked

Viewed 445 times

1

I have two objects from the Amazons3uploadservice classes and Databaseuploadservice and both implement the Uploadservice interface. The uploading class has the two objects injected by the Spring container.

The problem is that the container cannot inject the dependencies correctly and the following error occurs:

 Can not set br.com.manager.domain.service.AmazonS3UploadService field br.com.manager.domain.service.ConfiguracaoService.amazonS3UploadService to com.sun.proxy.$Proxy67

I tried to use other notes like @Resource, @Inject, @Qualifier and currently use @Autowired

Note: I know it is not a good place to put files in the database, for various reasons, but as it is a project with study purpose, I put as an option.

  • I don’t know if you can set up the injection, but if you’re injecting both implementations, there’s something wrong. Dependency injection has as its main motivation you only have one location to create the instances that implement interface. If the consumer really needs both implementations, use different interfaces or (more sensible) eliminate dependency injection for this consumer and these services: it makes no sense to centralize dependency if you will use multiple implementations.

  • @Rsinohara I analyzed the code after what you said and realized that it really needs to change and it makes no sense to have two implementations injected.

  • It makes sense to have a code that determines which implementation will be injected, plugin style. But injecting both really do not imagine case where it is necessary/useful.

  • I created an interface and implementation interface that will check where the file goes. And in the class that used the two objects I put the new implementation

2 answers

1


If you are injecting the two implementations, there is something wrong.

Dependency injection has as its main motivation you only have one location to create the instances that implement each interface.

If the consumer really needs both implementations, use different interfaces or (more sensible) eliminate dependency injection for this consumer and these services: it makes no sense to centralize dependency if you will use multiple implementations.

0

Although injecting the two implementations in the same point of the system is strange, the problem had nothing to do with it. You probably asked for the injection using concrete attributes, while you should have used the interface as attribute types. That way, all you had to do was put @Qualifier on top of each of the attributes that the injection would be done correctly.

Alberto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.