Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't Spring really support Interface injection at all?

I know that Spring doesn't supports Interface injection and I've read that many a times.

But today as I came across an article about IOC by Martin Fowler (link), it seems using ApplicationContextAware in Spring is some what similar to the Interface injection.

when ever Spring' context reference is required in our Spring bean, we'll implement ApplicationContextAware and will implement the setApplicationContext(ApplicationContext context) method, and we'll include the bean in the config file. Is not this the same as Interface injection, where where telling the Spring to inject (or), say, pass the reference of the context into this bean?

Or I m missing something here? Thanks for any information!

ManiKanta

like image 499
manikanta Avatar asked May 13 '10 13:05

manikanta


People also ask

Does Spring support interface injection?

There are three types of injection: Constructor, Setter and Interface. Spring doesn't support the latest directly(as I have observed people saying). So how is it done exactly?

Can interface be injected?

Maybe this is nitpicking but you can't inject an interface. You can only inject an object that implements an interface.

Should Spring services have interfaces?

with Spring Boot and libraries like lombok these days. So, it is not mandatory to create interfaces for Service, DAO but it is preferred if you are working on a fairly medium code base where there are multiple developers and possibly clients consuming those APIs outside of the application as well.

Can we create Bean of interface in Spring?

Bean creation via constructor. When creating a bean using the constructor approach, all normal classes are usable by Spring and compatible with Spring. That is, the class being created does not need to implement any specific interfaces or be coded in a specific fashion. Just specifying the bean class should be enough.


1 Answers

If you mean interface injection as defined on wikipedia, spring supports it out of the box for ResourceLoaders, ApplicationContexts, MessageSource, and others, with the interfaces ResourceLoaderAware, ApplicationContextAware, MessageSourceAware, respectively.

It is also possible to extend this mechanism with new interfaces an depedencies by registering a BeanPostProcessor.

The Spring reference manual explains this capability (and when one should (not) use it) quite clearly. BTW, I have generally found the spring reference manual to be much more reliable than what 'someone on the internet' says.

like image 69
meriton Avatar answered Oct 22 '22 00:10

meriton