spring and interfaces

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)?

Asked by: Emily124 | Posted: 28-01-2022

Answer 1

The Dependency Inversion Principle explains this well. In particular, figure 4.

A. High level modules should not depend on low level modules. Both should depend upon abstractions.

B. Abstraction should not depend upon details. Details should depend upon abstractions.

Translating the examples from the link above into java:

public class Copy {
    private Keyboard keyboard = new Keyboard(); // concrete dependency
    private Printer printer = new Printer();    // concrete dependency
    public void copy() {
        for (int c = keyboard.read(); c != KeyBoard.EOF) {

Now with dependency inversion:

public class Copy {
     private Reader reader; // any dependency satisfying the reader interface will work
     private Writer writer; // any dependency satisfying the writer interface will work
     public void copy() {
        for (int c = reader.read(); c != Reader.EOF) {
     public Copy(Reader reader, Writer writer) {
         this.reader = reader;
         this.writer = writer;

Now Copy supports more than just copying from a keyboard to a printer.

It is capable of copying from any Reader to any Writer without requiring any modifications to its code.

And now with Spring:

<bean id="copy" class="Copy">
    <constructor-arg ref="reader" />
    <constructor-arg ref="writer" />

<bean id="reader" class="KeyboardReader" />
<bean id="writer" class="PrinterWriter" />

or perhaps:

<bean id="reader" class="RemoteDeviceReader" />
<bean id="writer" class="DatabaseWriter" />

Answered by: Thomas703 | Posted: 01-03-2022

Answer 2

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.

Answered by: Miller446 | Posted: 01-03-2022

Answer 3

Most of the answers here are some form of "You can easily swap out implementations", but what I think they fail to answer is the why? part. To that I think the answer is almost definitively testability. Regardless of whether or not you use Spring or any other IOC framework, using Dependency Injection makes your code easier to test. In the case of say a writer rather than a PrinterWriter, you can Mock the Writer interface in a Unit test, and ensure that your code is calling it the way you expect it to. If you depend directly on the class implementation, your only option is to walk to the printer and check it, which isn't very automated. Furthermore, if you depend upon the result of a call to a class, not being able to Mock it may prevent you from being able to reach all code paths in your test, thus reducing their quality (potentially) Simply put, you should decouple Object graph creation from application logic. Doing so makes your code easier to test.

Answered by: Julian937 | Posted: 01-03-2022

Answer 4

No one has mention yet that in many occasions won't be necessary to create an interface so that the implementing class can be switched quickly because simply there won't be more than one implementing class.

When interfaces are created without need, classes will be created by pairs (interface plus implementation), adding unnecessary boilerplate interfaces and creating potential dependency confusions because, on XML configuration files, components will be sometimes referenced by its interface and sometimes by its implementation, with no consequences at runtime but being incoherent regarding code conventions.

Answered by: Kelvin911 | Posted: 01-03-2022

Answer 5

You may probably want to try using it for yourself to be better able to see this, it may not be clear from the docs how Spring encourages interface use.

Here are a couple of examples:

  1. Say you're writing a class that needs to read from a resource (e.g., file) that may be referenced in several ways (e.g., in classpath, absolute file path, as a URL etc). You'd want to define a org.springframework.core.io.Resource (interface) property on your class. Then in your Spring configuration file, you simply select the actual implementation class (e.g., org.springframework.core.io.ClassPathResource, org.springframework.core.io.FileSystemResource, org.springframework.core.io.UrlResource etc). Spring is basically functioning as an extremely generic factory.

  2. If you want to take advantage of Spring's AOP integration (for adding transaction interceptors for instance), you'll pretty much need to define interfaces. You define the interception points in your Spring configuration file, and Spring generates a proxy for you, based on your interface.

These are examples I personally have experience with. I'm sure there are much more out there.

Answered by: Marcus334 | Posted: 01-03-2022

Answer 6

it's easy to generate proxies from interfaces.

if you look at any spring app, you'll see service and persistence interfaces. making that the spring idiom certainly does encourage the use of interfaces. it doesn't get any more explicit than that.

Answered by: Grace520 | Posted: 01-03-2022

Answer 7

Writing separate interfaces adds complexity and boilerplate code that's normally unnecessary. It also makes debugging harder because when you click a method call in your IDE, it shows the interface instead of the implementation. Unless you're swapping implementations at runtime, there's no need to go down that path.

Tools like Mockito make it very easy to test code using dependency injection without piling on interfaces.

Answered by: Rubie512 | Posted: 01-03-2022

Answer 8

Spring won't force you to use interfaces anywhere, it's just good practice. If you have a bean that has a some properties that are interfaces instead of concrete classes, then you can simply switch out some objects with mockups that implement the same interface, which is useful for certain test cases.

If you use for example the Hibernate support clases, you can define an interface for your DAO, then implement it separately; the advantage of having the interface is that you will be able to configure it using the Spring interceptors, which will allow you to simplify your code; you won't have to write any code cathing HibernateExceptions and closing the session in a finally segment, and you won't have to define any transactions programmatically either, you just configure all that stuff declaratively with Spring.

When you're writing quick and dirty apps, you can implement some simple DAO using JDBC or some simple framework which you won't end up using in the final version; you will be able to easily switch those components out if they implement some common interfaces.

Answered by: Melanie229 | Posted: 01-03-2022

Answer 9

If you don't use interfaces you risk an autowiring failure: Sometime Spring creates a Proxy class for a Bean. This Proxy class is not a child class of the service implementation but it re-implements all of its interfaces. Spring will try to autowire instances of this Bean, however this Proxy class is incompatible with the Bean class. So declaring a field with Bean class can lead to "unsafe field assignement" exceptions.

You cannot reasonably know when Spring is going to Proxy a service (nor should you), so to protect yourself against those surprises, your best move is to declare an interface and use this interface when declaring autowired fields.

Answered by: Julia965 | Posted: 01-03-2022

Similar questions

Spring and Java interfaces

While reading some advanced book on developing the enterprise applications, I constantly see the following pattern that could be illustrated by the following example:. public interface Oracle { String defineMeaningOfTheLife(); } public class BookwormOracle implements Oracle { public String defineMeaningOfTheLife() { return "Use life, dude!"; } } And the main function...

ruby - question about java interfaces

Let's say I have the following ruby code : def use_object(object) puts object.some_method end and , this will work on any object that responds to some_method,right? Assuming that the following java interface exists : interface TestInterface { public String some_method(); } Am I right to presume that interfaces are java's way...

java - JPA mapping interfaces

I am having trouble creating a mapping when the List type is an interface. It looks like I need to create an abstract class and use the discriminator column is this the case? I would rather not have to as the abstract class will just contain an abstract method and I would rather just keep the interface. I have an interface lets call it Account public interface Account { public void doStuff(); }

java - How do I inherit from multiple extending generic interfaces?

I have a few classes such that: public class XMLStatusMessage extends XMLMessage {} public abstract class XMLMessage implements IMessage {} public interface IMessageListener { public void onMessage( IMessage message ); } public interface XMLMessageListener &lt;T extends XMLMessage&gt; extends IMessageListener { public void onMessage( T message ); } public interface XMLStatusMessageListener ...

oop - Java Interfaces?

Closed. This question does not meet Stack Overflow guid...

Best way to get started on simple 3D user interfaces using Java?

I'm writing a time management application and I have an idea for presenting timelines and todo items in 3D. Visually, I imagine this as looking down a corridor or highway in 3D, with upcoming deadlines and tasks represented as signposts - more important items are larger and upcoming deadlines are nearer. I want to do this in Java, however I have no idea how to begin. For example, I would like to be able to render t...

java - Why are interfaces preferred to abstract classes?

I recently attended an interview and they asked me the question "Why Interfaces are preferred over Abstract classes?" I tried giving a few answers like: We can get only one Extends functionality they are 100% Abstract Implementation is not hard-coded They asked me take any of the JDBC api that you use. "Why are they Interfaces?". Can I get a better answer for t...

java - Scala and interfaces

In Java I would typically declare my entire domain as interfaces, possibly with some kind of Factory to get me implementations. This is partly because I am so old I can remember when some persistence layers required implementation classes to subclass a specific class but also so that I can easily: mock objects for testing purposes proxy objects at runtime if nec...

java - What methods and interfaces do you (almost) always implement in classes?

Which methods and interfaces do you always implement in your classes? Do you always override equals()? If you do, do you also do hashcode()? toString()? Do you make it a habit to implement the Comparable interface? I've just written some code where I needed to implement compareTo() and override equals() to get my program to work in a sane manner; I now start seeing ways of using these everywhere... ...

java - Interfaces declaring methods with abstracts as parameters

I have this question about best practices in following examples: interface Request; interface Service { void process(Request request) } class MyService implements Service; class YourService implements Service; class MyRequest implements Request; class YourRequest implements Request; But how to ensure that MyService will always receive MyRequest and YourS...

java - JiBX: How do I keep using interfaces in my code?

How can I keep my using interfaces in classes I want to use JiBX binding with? Example: I have this very simple model in java: public interface A { B getB(); void setB(B b); } public interface B { String getData(); void setData(String data); } public class AImpl implements A { B b; @Override public B getB() { return b; } @Override public void setB(...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)