Why we are using interface in spring MVC pattern? - java

I am new to spring MVC , I have downloaded a small spring MVC project . The project is executing fine but it this project interfaces and classes are being used .
like
public interface EmployeeService {
public void addEmployee(Employee employee);
public List listEmployeess();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
And
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addEmployee(Employee employee) {
employeeDao.addEmployee(employee);
}
public List listEmployeess() {
return employeeDao.listEmployeess();
}
public Employee getEmployee(int empid) {
return employeeDao.getEmployee(empid);
}
public void deleteEmployee(Employee employee) {
employeeDao.deleteEmployee(employee);
}
}
My doubt is if we are using EmployeeServiceImpl what is the need of implementing EmployeeService ? same thing is there in EmployeeDao and EmployeeDaoImpl.

Interfaces are always a good practice for decoupling, but also, when speaking about Spring, there are several features you can use having interfaces rather than concrete classes.
A big advantage is proxying - Spring AOP.
You can find more information here: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html
There are other advantages, like post processing and things like that, but I think you will have an interesting reading on Spring AOP.

Weather spring mvc or not, one should always code to interface. Interface gives me better readability when i just want to see what the class does instead of worrying about how it does it, kind of API exposed to outer world.
Another benefit is there could be multiple implementations of 'how to do' it and spring helps to switch easily between multiple implementations. For e.g. you could have one more implementation of EmployeeService say FullTimeEmployeeServiceImpl, RemoteEmployeeServiceImpl.
Now if you have client class which uses EmployeeService:
class EmployeeManager{
private EmployeeService service;
}
you can inject any of bean here
<bean id="employeeManager" class="com.abc.EmployeeManager">
<property name="service" ref="fullTimeEmployee | remoteEmployee" >
</bean>
<bean id="fullTimeEmployee" class="com.abc.FullTimeEmployeeServiceImpl" />
<bean id="remoteEmployee" class="com.abc.RemoteEmployeeServiceImpl" />

A few principles that are part of the SOLID acronym for OO design apply to this:
Liskov substitution principle - you should be able substitute any subtype of T without affecting the outcome of the problem. E.g., if you call a method that returns a List<>, and the underlying implementation switches from returning an ArrayList<> to a LinkedList<>, your program should still perform in the same manner. Basically, you should design your classes so that client dependencies can be substituted with subclasses without the client knowing about the change. Here is a short snippet from the wiki page:
Substitutability is a principle in object-oriented programming. It
states that, in a computer program, if S is a subtype of T, then
objects of type T may be replaced with objects of type S (i.e.,
objects of type S may substitute objects of type T) without altering
any of the desirable properties of that program (correctness, task
performed, etc.)
Dependency inversion principle - The main idea is that you isolate the class behind a boundary based upon the abstractions it depends on. That way if any of the details that sit behind those abstractions change, the class will be unaffected.
In object-oriented programming, the dependency inversion principle
refers to a specific form of decoupling software modules. When
following this principle, the conventional dependency relationships
established from high-level, policy-setting modules to low-level,
dependency modules are inverted (i.e. reversed), thus rendering
high-level modules independent of the low-level module implementation
details. The principle states
A. High-level modules should not depend on low-level modules.
Both should depend on abstractions.
B. Abstractions should not depend on details.
Details should depend on abstractions.

It don't have much .to do with Spring or MVC.It is good practice to design with interfaces, so that implementation can be changes easily. It provides loose coupling and if you are using spring you can siimply change implementation. Whenver needed.
Also , it helps during testing with Junit. You can easily mockup your dao.

It is recommended to write code against interfaces instead specific implementations.
This way, the client code doesn't know the specific implementations but only knows the contract.
Regarding Spring, you generally have to use interfaces since Spring often needs to create Java proxies and this can be done only for classes that implement interfaces.

Related

Why do we need to use beans in spring boot? [duplicate]

This question already has answers here:
What in the world are Spring beans?
(14 answers)
Closed last month.
I am just getting started with spring boot and I don't get why would I use beans instead of creating my own objects. what is the difference between an object that I created and the one spring created(bean)?
I tried making a bean and it takes more coding than creating a normal object, I had to learn how to use ApplicationContext,getBean etc..
Short answer: Spring bean = object.
Long answer: It's easier to allow Spring to inject all of your objects into the classes that depend on them, rather then creating your own IoC container.
Read more about it here: https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/beans.html
#Bean annotation is basically used to define your class as Object yes you re right that creatiing a bean initally requires a more coding that directly creating a object of the class but have you ever think suppose you have created the object by using new keyword and you have created this object at many places suppose 1000 places and if you have to change anything in your object that will complicate you because you have to go all 1000 places and change it but when you are using bean you need to make those change at single place and at all other places it will be reflectd automatically also in this case we donot need to compile your whole code that's why we use #bean also it will be very helpfull to make your code losselly coupled
Spring is a framework that allows you to use dependency inject. This means that the framework can build class instances (beans) for you and you simply declare the dependencies between the beans. I suggest you to get familiar with dependency injection.
#Bean
public class SuperHeavyService {
// the datasource is build by the framework due to configuration
private Datasource connection;
private HttpClient client;
//
public SuperHeavyService(Datasource connection, HttpClient client) {
this.connection = connection;
this.client = client;
}
}
#Bean
public class HttpClient {
}
The example above shows you that the SuperHeavyService is created by the framework and the framework will inject the requires types using the constructor of the SuperHeavyService class. This is dependency injection.
We use bean mainly to achive loose coupling.
When you are creating objects by yourself, then these objects are tight coupled.
Imagine an application with dozens or even hundreds of classes. Sometimes we want to share a single instance of a class across the whole application, other times we need a separate object for each use case, and so on.
Managing such a number of objects is nothing short of a nightmare. This is where inversion of control comes to the rescue.
Instead of constructing dependencies by itself, an object can retrieve its dependencies from an IoC container. All we need to do is to provide the container with appropriate configuration metadata.
With the IOC, you can achieve loose coupling.
Loose coupling means that classes are mostly independent. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled. In order to over come from the problems of tight coupling between objects, spring framework uses dependency injection mechanism with the help of POJO/P model and through dependency injection its possible to achieve loose coupling.
Example : If you change your shirt, then you are not forced to change your body – when you can do that, then you have loose coupling. When you can’t do that, then you have tight coupling. The examples of Loose coupling are Interface, JMS.
Java program to illustrate loose coupling concept
public interface Topic
{
void understand();
}
class Topic1 implements Topic {
public void understand()
{
System.out.println("Got it");
}
} class Topic2 implements Topic {
public void understand()
{
System.out.println("understand");
}
} public class Subject {
public static void main(String[] args)
{
Topic t = new Topic1();
t.understand();
}
}
Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.
Hope it helps.

Spring, is there a way to get around not being able to extend 2 classes in Java?

I have an integration test with the following signature:
#SpringBootTest(classes = Example.class)
#ActiveProfiles("test")
public class CoolTest_IntegrationTest extends MyTestFrameworkAbstractClass {
PrismIntegrationFramework is an abstract class with a bunch of setup methods to make testing easier for people on my team.
Now, in Spring I heavily rely on DynamicPropertySource for injection dynamic Ip addresses, etc coming from my test containers.
Ideally, I want a separate "test harness" that I could inject/invoke based on the type of test. IE - I would have a GraphDBHarness that would be invoked when I write graph database integration tests.
#SpringBootTest(classes = GraphClient.class)
#ActiveProfiles("test")
public class CoolTest_IntegrationTest extends MyTestFrameworkAbstractClass extends GraphDBHarness {
I know the above is invalid, but if this was valid then I would internally have something like :
public abstract class GremlinTestHarness {
#DynamicPropertySource
static void executeDynamicPropertyInjection(DynamicPropertyRegistry registry) {
registry.add(
GREMLIN_SERVER_KEY, () -> SupportedContainers.gremlinServer.getContainerIpAddress());
registry.add(GREMLIN_SERVER_PORT, () -> SupportedContainers.gremlinServer.getFirstMappedPort());
}
}
So in theory, if I had N of these, then I could inject the things I need or make the things I need available at will. Is this possible in Spring somehow?
Short answer: There's no way around single inheritance of classes in Java. This was done purposely to avoid the Diamond Problem.
Long answer: You can take advantage of multiple inheritance of interfaces. Also, just about every problem where you think you need inheritance, you can resolve with composition. In general, inheritance - although a necessary evil at times - violate encapsulation and is more problematic that you might think. Without knowing much about your specific implementation details, on the surface, your problem seems to fit the case where composition over inheritance is the way to go. I normally do a quick "is-a" check as the first step to see if inheritance makes sense. In your case:
CoolTest_IntegrationTest is-a MyTestFrameworkAbstractClass doesn't pass my logical test, because a test class is not a framework. A test class USES a framework. Even saying that a framework has-a test might not make much sense either. However, that is much better than tests inheriting from an abstract framework. The CoolTest_IntegrationTest is-a GraphDBHarness doesn't pass my initial test either. A test also uses a DB harness, which implies composition.
Again, it seems you are trying to use inheritance for all the wrong reasons. Accessing fields/methods in a class is not in itself a good reason for inheritance. If you have an abstract framework class, you should only extend to make more specific types of frameworks, not to create test classes.
Use Dependency Injection to pass these items to your test class (i.e. DB harness) instead of using inheritance only to gain access to its fields and methods.
That said, you could use single inheritance and create a inheritance chain where class A extends B and it extends C (instead of class A extending B and C). Again, in your case, I don't think this is the right approach.

Need Of Dao And Service Interfaces

I am new to spring Mvc and in a lot of tutorials, I found there is a Dao interface like this
public interface StudentDAO {
public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);
}
and also services like this
public interface StudentService {
public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);
}
And there are implementations for these interfaces.
My question is why we need interfaces rather than direct implementation classes?
I'm glad to see someone questioning that practice.
Spring Framework introduced long time ago the pattern of defining interfaces for their managed service / DAO beans. I think that practice was introduced due to limitations in the technology they used to create dynamic proxies.
When a Spring-managed bean is defined, the framework creates a proxy to the underlying instance with the purpose of decorating it with cross-cutting functionality using AOP techniques. Apparently, the tools they used to implement those proxies in the early versions of Spring Famework required an interface to create the proxy out of it.
This requirement no longer holds in the latest versions of Spring Framework and you're safe to dispose of those useless interfaces.
The reason for ease of testing does not hold nowadays, either, as mocking frameworks like Mockito are also capable of mocking concrete classes.
In addition, you can use the #Primary annotation to replace the real implementation with a custom mock in a testing context.
For those reasons, I would scrap interfaces for internal service and DAO classes that will never have multiple co-existing valid implementations.
Keep interfaces for design patterns that really need them.
In theory, it creates interfaces to decrease the coupling. In other words you create interfaces that are the communication contracts. And with that you can have more of an implementation for the same contract. Example: In PersonDao you can have implementation with hibernate and one with native SQL. With that in places where you used, you only inject interace and CDI itself solves the implementation, then you easily change the implementation without affecting the places where it is used interfaces.
In practice in my projects, depending on the situation, do not create the interfaces, but I will emphasize, it depends on the project. Example: A DAO in the majority of the time it never changed its implementation, that is, I see no need to create the interfaces in these cases directly implement the concrete classes.
The post Jiri Tousek is an example for the use of interfaces. However in my tests, I always use the complete flow, including the database.
Perhaps the simplest concrete illustration for the need is testing.
With the DAO interface, you can test your application's logic without the need to have a DB running that's accessible from the machine running tests, simply by swapping your DAO implementation for a dummy one during tests. That dummy implementation can then provide consistent data for tests that doesn't change between test runs, cannot be overwritten in DB by accident, is versioned in you Git/SVN/whatever etc.
In general, this is part of the Program to an interface, not an implementation design principle.
In my experience, this separation of interface vs. implementation is a good idea even if you're never going to have multiple implementations, because it encourages programmers to think more deeply about the contract of the class.
Note that the principle is not universally accepted, here are some counter-arguments for example.
if you are doing project it includes some database so you must define function in interface in this way Which you use is easily seen.

Dependency Injection - Proper use of interfaces? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been reading about DI and best practices, and still haven't found the answer to this question. When should I use interfaces?
Some developers suggest to add interface for every object that is being injected. This would make a modular application.
Some other are against this.
So my question is which one is correct?
EDIT:
Below are the two sides, I still don't see the advantage of using interfaces. In both cases I can easily mock classes, and change the implementations
Using interfaces
bind(IUserStorage.class).to(UserStorage.class);
// Unit test
bind(IUserStorage.class).to(Mock(UserStorage.class));
Not using interfaces
bind(UserStorage.class).to(UserStorage.class);
// Unit test
bind(UserStorage.class).to(Mock(UserStorage.class));
I can't believe using interfaces is againt OOP principles!
I would definitely use interfaces in this scenario. It means you're loosely coupling your components and can easy mock and/or substitute alternatives. Lots of DI frameworks will use the interfaces in order to provide additional functionality (e.g. create proxy objects mapped to the real objects, but with additional features).
As such I would try and use interfaces for all but the most trivial of injected objects. At some stage you're going to want to make use of substitutability, framework code generation etc. and retrofitting interface usage is an additional pain that it's easy to avoid at the beginning of a project.
Interface based design is the cornerstone of IoC, here is a short description of Interface-based design (Sorry that I'm referencing my own blog, but I just finished an article about this, it was an extract from my MS Thesis):
Nandigam et al. defines Interface-based design as "a way of developing
object-oriented systems where one consciously and proactively defines
and uses interfaces wherever possible in a design to reap the benefits
of designing with interfaces" [Nan09]. Applications with an
interface-based design follow the principle "program to an interface,
not an implementation". This principle brings the following benefits
to the resulting system [Dav03]: flexibility (describes the system
robustness to change), extensibility (the ease with which a system may
accommodate additions) and pluggability (the ability that allows
substitutions of objects with identical interfaces at run-time).
Once you mix interface design with IoC you obtain the following benefits:
Tasks are decoupled from the implementation.
Increases modularity where modules rely on other modules solely on their contracts (interfaces).
Increases pluggability and replacing a module does not have a cascading effect on other modules.
To answer your question, I would use interfaces for different types of modules. For example, one per service or repository.
I do not create interfaces for controllers or Model classes (MVC apps).
All this, as a side effect, facilitates testing.
If you use interfaces or at least abstract/inheritable classes you can change the behaviour of the program by an easy exchange of the implementation (inject another class) in the DI/IoC config.
Using interfaces is a good practice (imho). This is especially very important if you are writing UnitTests which needs mocks. It is much harder to write UnitTests with a good coverage (not to say impossible in most "real world" cases) if you're not using interfaces.
I think you should use an interface if there might be a chance that the injected part could change. It should be easy to extend your implementation, see Open-Closed-Principle. => This will require the exchange of modules/parts/implementations... ask yourself what would happen if your class has no virtual functions to override and you are forced to change the implementation.
I would use interfaces at least for the public classes / parts of your code (the parts other programmers would use).
Having a look at your sample. The problem is at the wiring part and not only the binding of a class as (default) implementation of an interface (binding works, but wiring could break).
For example if you have 2 implementations (C# sample here, should be the same in Java etc., too):
public interface IUserStorage
{
void Write(object something);
}
public class UserStorageTextFile : IUserStorage
{
public void Write(object something) { ... }; // stores to text file
}
public class UserStorageDB : IUserStorage
{
public void Write(object something) { ... }; // stores to DB
}
public class MyStorageClient
{
public MyStorageClient(IUserStorage storage) { ... } // copy to private field and use it etc.
}
Depending on your IoC it should be easy to wire
an instance of MyStorageClient to your binding of IUserStorage.
bind(IUserStorage.class).to(UserStorageDB.class); // Java sample, eh?
But if your MyStorageClient is strongly forced to use DB already...
public class MyStorageClient
{
public MyStorageClient(UserStorageDB storage) { ... } // copy to private field and use it etc.
}
... it is imposible to wire it up with the UserStorageTextFile class except the UserStorageTextFile is inherited from UserStorageDB... but why should you have a dependency to e.g. Oracle drivers (required by UserStorageDB) if you only want to write a simple text file?
I think the sample is clear enough and shows up the benefits of using interfaces...
but if not... try to do this:
bind(UserStorageDB.class).to(UserStorageTextFile.class);
// and in another config/module/unitTest
bind(UserStorageTextFile.class).to(Mock(UserStorageDB.class));
// and try to wire it against your client class, too (both ways, meaning one config for TextFile and load a config for the DB after changing only the configuration)
Your question states "some developers [are for this]" and "some developers [are against this]", so there is no right answer. But this is why I agree that interfaces are overused
If you are creating a library, choosing when to use interfaces is important. It is harder to create a maintainable contract when you don't control how your code is consumed.
If, however, you are creating an application, it less likely to require an interface, because the public interface of a class can serve as the maintainable contract to consuming code. Let's say version 1 looks like this:
public class UserStorage
{
public void Store(User user) { /* ... */ }
}
You don't even need refactoring tools to change it to this:
public interface UserStorage
{
public void Store(User user);
}
class TheImplementation implements IUserStorage
{
public void Store(User user) { /* ... */ }
}
Then you can easily use refactoring tools to rename the interface to IUserStorage.
So when you are writing non-library code, you can usually get away with a class until you need swappable implementations, decorators, etc. You should use an interface when the public interface of the class does not suit your needs. (For example, see the interface segregation principle)
In short - having an interface that is 1:1 with a class is unnecessary indirection in application code.

Avoiding tight coupling between Service classes

Say I have 2 service classes:
UserService
ProductService
Is it wrong if within my ProductService class I inject the UserService?
public class ProductserviceImpl implements ProductService {
#Autowired
UserService userService;
#Override
public void someThing() {
..
userService.otherThing(..);
..
}
}
I know as an alternative I could create yet another class that injects both UserService and ProductService, but coming up with a name for this class is very tricky :) Is there a name for these types of classes in the SOA world?
1) Is it wrong if within my ProductService class I inject the UserService?
There is nothing wrong with this per se, with the following caveats:
Be aware that you could be potentially heading in the direction of one class doing too much (here, the ProductService)
Be careful that you don’t introduce cyclic dependencies (you should not have UserService also depend on ProductService)
Limit tight coupling by wiring your dependency to the interface rather than the concrete class (here you are autowiring UserService instead of UserServiceImpl, which is good)
2) Is there a name for this type of class (that injects both UserService and ProductService) ?
Yes, as was mentioned, you could call this class a Mediator since the Mediator Pattern seems to describe this.
You can have both low-level services and high-level services, with the low-level ones (ProductService, UserService) injected into the high-level ones (say, PurchaseOrderService or PurchaseOrderMediator). Alternatively, for this particular case you might think of the product service as being a single high-level service that depends on UserService. At that point it’s more about which construct is more cohesive in the context of your business logic and your application.
For me, there's no problem to inject a service into another one. That's the point with services and SOA as you said.
Services can help each others in order to give you the final result. Besides, as told JB Nizet, if there is no cyclic dependencies, no problem.
What you are describing is called Mediator Pattern.
Btw what is SOA?
Injecting one service into another using spring like you have mentioned will couple, the 2 services only to the extent of the interface used.
If you need more decoupling, think of using a message to pass between the 2 services.
Message can be strongly typed like a value object/xml with schema
or weakly typed like a HashMap
While weakly typed messages can increase the decoupling, it means you and your client will forfeit compile time checking and debugging issues will be cumbersome at runtime
What you describe is object oriented integration and most likely not a SOA one. The fact that you may get (and should avoid) cyclic dependencies demonstrate that.
If you're services know other service Java level Interfaces you are also in a big risk to introduce tight coupling.
For instance, what's the return type from the User service? is it yet another interface that belong to the User service? do you pass it around in the code of product service?

Categories