Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring and interfaces

Tags:

java

spring

I read all over the place about how Spring encourages you to use interfaces in your code. I don't see it. There is no notion of interface in your spring xml configuration. What part of Spring actually encourages you to use interfaces (other than the docs)?

like image 662
lowellk Avatar asked Nov 01 '08 23:11

lowellk


People also ask

What are the interfaces in Spring?

Spring Aware interfaces allow you to look into the inner workings of the Spring Framework. Through Spring Aware interfaces, you can access the Spring context, or Spring bean lifecycle events. Your Spring beans might require access to framework objects, such as ApplicationContext , BeanFactory , and ResourceLoader .

Should Spring services have interfaces?

So, if you ask me whether you should use an interface for your services, my answer would be no. The only exception is if you're either trying to use inversion of control, or you have multiple implementations to take care of.

Can we inject interface in Spring?

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

Can we use @autowired for interface?

If you try to use @Autowired on an interface, the Spring framework would throw an exception as it won't be able to decide which implementation class to use.


1 Answers

When you define an interface for your classes, it helps with dependency injection. Your Spring configuration files don't have anything about interfaces in them themselves -- you just put in the name of the class.

But if you want to inject another class that offers "equivalent" functionality, using an interface really helps.

For example, saying you've got a class that analyzes a website's content, and you're injecting it with Spring. If the classes you're injecting it into know what the actual class is, then in order to change it out you'll have to change a whole lot of code to use a different concrete class. But if you created an Analyzer interface, you could just as easily inject your original DefaultAnalyzer as you could a mocked up DummyAnalyzer or even another one that does essentially the same thing, like a PageByPageAnalyzer or anything else. In order to use one of those, you just have to change the classname you're injecting in your Spring config files, rather than go through your code changing classes around.

It took me about a project and a half before I really started to see the usefulness. Like most things (in enterprise languages) that end up being useful, it seems like a pointless addition of work at first, until your project starts to grow and then you discover how much time you saved by doing a little bit more work up front.

like image 88
Sean Schulte Avatar answered Oct 04 '22 13:10

Sean Schulte