-2

I'm new to Spring and I have a question about how it works.

Why is the interface instantiated in Spring framework and not the class that implements it?

I have seen several tutorials and they all do the same but I can not understand why

The interface:

public interface ILoginServicio {
    public String getLogin(String usuario, String contrasena);
    public boolean getMultiSearchResult(DirContext dirContext, String searchFilter, String searchBase);
    public boolean displayAttribute(String attrName, final Attributes attributes);
}

The class implementing the interface:

@Service
public class LoginServicioImpl implements ILoginServicio{

    @Autowired
    private Environment environment;

    @Override
    public String getLogin(String usuario, String contrasena) {
        ....
    }

    @Override
    public boolean getMultiSearchResult(DirContext dirContext, String searchFilter, String searchBase) {
        ...
        return flagActiveDirectory;
    }

    @Override
    public boolean displayAttribute(String attrName, Attributes attributes) {
        ....
        return flagActiveDirectory;
    }
}

Restcontroller class where the bean is injected to:

@RestController
public class Login {

    @Autowired
    ILoginServicio iLoginServicio;

    @RequestMapping("/login")
    public Respuesta<String> login(@RequestBody UsuarioLogin user){
        //.......
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Alejandro Herrera
  • 411
  • 1
  • 5
  • 22
  • "Why is the interface instantiated in Spring framework" ... well this is wrong and I wonder why you think that? Have tried your code? – Tom Jul 03 '19 at 16:53

1 Answers1

1

It is Liskov substitution principle. Basic reason is that it will give you flexibility.

Let's say you utilize to a MySQL database currently. However, 2 years later you want to migrate to MongoDB. There will be no change in the logic of your application. It will still flow the same, but the database vendor will be different. If implementations would be used then you'd have to replace all the current class variables with new implementati. However, when interfaces are used, you just implement a new one with the same method signatures and just configure Spring to use new one, instead of the old one.

Another non-Spring example. Let's say you have a list as follows. Using only the implementation will limit you. How? For example, if you will decide that ArrayList is not performing well and want to use LinkedList, then you have to change all the variable's data types and also solve issues like methods exist in ArrayList and not in LinkedList. As you can see, in a big codebase, it requires a lot of time.

ArrayList<String> data = new ArrayList<>();

However, using List interface, you can be sure that method existence issues or other data type issues won't happen because all the implementations must have the required methods.

List<String> data = new LinkedList<>();
Mansur
  • 1,661
  • 3
  • 17
  • 41