Spring boot service layer interface + implementation pattern - spring

In a typical CRUD application we could have entities such as users, orders, invoices etc.
For the service layer it's a common pattern to create the service interface and its implementation.
UserService
UserServiceImpl
OrderService
OrderServiceImpl
InvoiceService
InvoiceServiceImpl
I know it's a good practice to code in terms of interfaces, but for this particular case where the service implementation most probably won't change, do we really have to create an interface and its implementation with that ugly "Impl" suffix?
It might be that I just have a problem with that naming convention? Is there another way to address the design and creation of the service layer?
This might be a slightly different approach in the naming convention:
UserService
DefaultUserService
OrderService
DefaultOrderService
InvoiceService
DefaultInvoiceService
However, I feel that we are still coding in terms of interfaces "just" for the sake of coding in terms of interfaces in a situation where the implementations most probably won't change.

Related

Implement "cache tags pattern" in Spring

I have been searching for long time in the Internet, if Spring supports the "cache tag pattern" but seems it doesn't.... How do you implement this cache pattern in Spring???
An example of this cache pattern can be seen in Drupal cache tag implementation, I will create an example of how would that look
#Service
#AllArgsConstructor
class TicketService {
private final UserRepository userRepository;
private final ProductRepository productRepository;
private final TicketRepository ticketRepository;
#Cacheable(cacheNames = "global-tags-cache", tags = { "ticket:list", "user:#{user.id}", "product:#{product.id}"})
public List<TicketDto> findTicketsForUserThatIncludesProduct(User user, Product product) {
var tickets = ticketRepository.findByUserAndProduct(user, product);
}
#CacheEvict(cacheNames = "global-tags-cache", tags = "ticket:list")
public Ticket saveNewTicket(TicketRequestDto ticketRequestDto) { ... }
}
#Service
#AllArgsConstructor
class ProductService {
private final ProductRepository productRepository;
#CacheEvict(cacheNames = "global-tags-cache", tags = "product:#{productRequestDto.id}")
public Product updateProductInformation(ProductRequestDto productRequestDto() {
...
}
}
#Service
class NonTagCacheService() {
#Cacheable(cacheNames = "some-non-global-cache-store")
public Object doStrongComputation() { ... }
}
The idea is to handle the responsability of the "tag eviction" where it belongs to, for example TicketService wants its cache to be break when user is altered, or when any ticket is altered, or when the specified product is altered... TicketService doesn't need to know when or where Product is going to clear its tag
This pattern is strongly useful in Drupal, and makes its cache very powerfull, this is just an example, but one can implement its own tags for whatever reason he wants, for example a "kafka-process:custom-id"
As M. Deinum explained, Spring's Cache Abstraction is just that, an "abstraction", or rather an SPI enabling different caching providers to be plugged into the framework in order to offer caching capabilities to managed application services (beans) where needed, not unlike Security, or other cross-cutting concerns.
Spring's Cache Abstraction only declares fundamental, but essential caching functions that are common across most caching providers. In effect, Spring's Cache Abstraction implements the lowest common denominator of caching capabilities (e.g. put and get). You can think of java.util.Map as the most basic, fundamental cache implementation possible, and is indeed one of the many supported caching providers offered out of the box (see here and here).
This means advanced caching functions, such as expiration, eviction, compression, serialization, general memory management and configuration, and so on, are left to individual providers since these type of capabilities vary greatly from one cache implementation (provider) to another, as does the configuration of these features. This would be no different in Drupal's case. The framework documentation is definitive on this matter.
Still, not all is lost, but it usually requires a bit of work on the users part.
Being that the Cache and CacheManager interfaces are the primary interfaces (SPI) of the Spring Cache Abstraction, it is easy to extend or customize the framework.
First, and again, as M. Deinum points out, you have the option of custom key generation. But, this offers no relief with respect to (custom) eviction policies based on the key(s) (or tags applied to cache entries).
Next, you do have the option to get access to the low-level, "native" cache implementation of the provider using the API, Cache.getNativeCache(). Of course, then you must forgo the use of Spring Cache Annotations, or alternatively, the JCAche API Annotations, supported by Spring, which isn't as convenient, particularly if you want to enable/disable caching conditionally.
Finally, I tested a hypothesis to a question posted in SO not long ago regarding a similar problem... using Regular Expressions (REGEX) to evict entries in a cache where the keys matched the REGEX. I never provided an answer to this question, but I did come up with a "generic" solution, implemented with 3 different caching providers: Redis, Apache Geode, and using the simple ConcurrentMap implementation.
This involved a significant amount of supporting infrastructure classes, beginning here and declared here. Of course, my goal was to implement support for multiple caching providers via "decoration". Your implementation need not be so complicated, or rather sophisticated, ;-)
Part of my future work on the Spring team will involve gathering use cases like yours and providing (pluggable) extensions to the core Spring Framework Cache Abstraction that may eventually find its way back into the core framework, or perhaps exist as separate pluggable modules based on application use case and requirements that our many users have expressed over the years.
At any rate, I hope this offers you some inspiration on how to possibly and more elegantly handle your use case.
Always keep in mind the Spring Framework is an exceptional example of the Open/Closed principle; it offers many extension points, and when combined with the right design pattern (e.g. Decorator, not unlike AOP itself), it can be quite powerful.
Good luck!

Identifying Spring MVC architecture pattern

I'm working through a spring mvc video series and loving it!
https://www.youtube.com/channel/UCcawgWKCyddtpu9PP_Fz-tA/videos
I'd like to learn more about the specifics of the exact architecture being used and am having trouble identifying the proper name - so that I can read further.
For example, I understand that the presentation layer is MVC, but not really sure how you would more specifically describe the pattern to account for the use of service and resource objects - as opposed to choosing to use service, DAO and Domain objects.
Any clues to help me better focus my search on understanding the layout below?
application
core
models/entities
services
rest
controllers
resources
resource_assemblers
Edit:
Nathan Hughes comment clarified my confusion with the nomenclature and SirKometa connected the architectural dots that I was not grasping. Thanks guys.
As far as I can tell the layout you have mentioned represents the application which communicates with the world through REST services.
core package represents all the classes (domain, services, repositories) which are not related to view.
model package - Assuming you are aiming for the typical application you do have a model/domain/entity package which represents your data For example: https://github.com/chrishenkel/spring-angularjs-tutorial-10/blob/master/src/main/java/tutorial/core/models/entities/Account.java.
repository package - Since you are using Spring you will most likely use also since spring-data or even spring-data-jpa with Hibernate as your ORM Library. It will most likely lead you to use Repository interfaces (author of videos you watch for some reason decided not to use it though). Anyway it will be your layer to access database, for example: https://github.com/chrishenkel/spring-angularjs-tutorial-10/blob/master/src/main/java/tutorial/core/repositories/jpa/JpaAccountRepo.java
service package will be your package to manipulate data. It's not the best example but this layer doesn't access your database directly, it will use Repositories to do it, but it might also do other things - it will be your API to manipulate data in you application. Let's say you want to have a fancy calculation on your wallet before you save it to DB, or like here https://github.com/chrishenkel/spring-angularjs-tutorial-10/blob/master/src/main/java/tutorial/core/services/impl/AccountServiceImpl.java you want to make sure that the Blog you try to create doesn't exist yet.
controllers package contain all classes which will be used by DispacherServlet to take care of the requests. You will read "input" from the request, process it (use your Services here) and send your responses.
resource_assemblers package in this case is framework specific (Hateoas). As far as I can tell it's just a DTO for your json responses (for example you might want to store password in your Account but exposing it through json won't be a good idea, and it would happen if you didn't use DTO).
Please let me know if that is the answer you were looking for.
This question may be of interest to you as well as this explanation.
You are mostly talking about the same things in each case, Spring just uses annotations so that when it scans them it knows what type of object you are creating or instantiating.
Basically everything request flows through the controller annotated with #Controller. Each method process the request and (if needed) calls a specific service class to process the business logic. These classes are annotated with #Service. The controller can instantiate these classes by autowiring them in #Autowire or resourcing them #Resource.
#Controller
#RequestMapping("/")
public class MyController {
#Resource private MyServiceLayer myServiceLayer;
#RequestMapping("/retrieveMain")
public String retrieveMain() {
String listOfSomething = myServiceLayer.getListOfSomethings();
return listOfSomething;
}
}
The service classes then perform their business logic and if needed, retrieve data from a repository class annotated with #Repository. The service layer instantiate these classes the same way, either by autowiring them in #Autowire or resourcing them #Resource.
#Service
public class MyServiceLayer implements MyServiceLayerService {
#Resource private MyDaoLayer myDaoLayer;
public String getListOfSomethings() {
List<String> listOfSomething = myDaoLayer.getListOfSomethings();
// Business Logic
return listOfSomething;
}
}
The repository classes make up the DAO, Spring uses the #Repository annotation on them. The entities are the individual class objects that are received by the #Repository layer.
#Repository
public class MyDaoLayer implements MyDaoLayerInterface {
#Resource private JdbcTemplate jdbcTemplate;
public List<String> getListOfSomethings() {
// retrieve list from database, process with row mapper, object mapper, etc.
return listOfSomething;
}
}
#Repository, #Service, and #Controller are specific instances of #Component. All of these layers could be annotated with #Component, it's just better to call it what it actually is.
So to answer your question, they mean the same thing, they are just annotated to let Spring know what type of object it is instantiating and/or how to include another class.
I guess the architectural pattern you are looking for is Representational State Transfer (REST). You can read up on it here:
http://en.wikipedia.org/wiki/Representational_state_transfer
Within REST the data passed around is referred to as resources:
Identification of resources:
Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server may send data from its database as HTML, XML or JSON, none of which are the server's internal representation, and it is the same one resource regardless.

Service layer in spring - autowire all services

I was thinking about some of my services.
Some of them looks like this:
#Service
public class UserService {
#Autowired
UserDao dao;
#Autowired
OtherService1 serv1;
#Autowired
OtherService2 serv2;
#Autowired
OtherService3 serv3;
....
}
I was thinking.. if this concept of autowiring other services into a single service is pretty common, why not creating a "Master-service" :
#Service
public class MasterService {
#Autowired
OtherService1 serv1;
#Autowired
OtherService2 serv2;
#Autowired
OtherService3 serv3;
...
#Autowired
LastService servN;
}
and autowiring this service in to all services.
#Service
public class AnyService {
#Autowired
MasterService masterSevice;
}
this way we wont have many services per service, but only a single one to rule them all..
Two questions rises:
1) Since masterService contain all services we have a loop in injection. can we solve it?
2) if the answer to question 1 is "yes" - is this "masterService" a good practice?
1) Spring is able to handle dependency loops in many cases, especially when not using constructor injections.
2) Despite this. You should absolutely avoid this design. It breaks many principles of good architecture:
Components should only have access to as few other components as needed. Demeter's Law
Separation of concerns. A service should not at the same time handle business logic, and presentation.
Abstraction levels. A service should not handle both a logical view of data, and a persistence view of it.
Breaking such principles may lead to bad situations such as:
Inability to follow code paths (a single request will go through 12 services in an order that is hard to understand and relies on many levels of conditional logic).
Difficulty to know which components rely on each-other.
Strongly coupled code (changing a low level service will lead to changes in high level services).
The advantages you gain from such a design are very small (you just avoid a few #Autowired annotations) and are not worth the risk.
Why would have a circular dependency? There is one service that contains all the other services, and no other service that contains it. Having said that, a circular dependency could be easily solved by setting the dependency as property and not as constructor arg.
I don't think so, it is nice pattern to declare kind of hierarchy (in endpoints for instance), but what are the pros of it in this way? You can Autowire every service that you want also without it.
1) MasterService doesn't necessarily contain a loop. If it does, then you'll run into problems, and it's much simpler not to construct your beans in a loop in the first place.
2) It's possible for this to be effective if you're injecting into lots of short-lived beans, but this approach has the downside that anyone who meddles with the MasterService instance can screw up the services for the other beans. You can hide this behind getter methods, but lumping everything together usually doesn't provide much benefit.
Instead, it's usually best to group related services together, maybe OtherService1 and OtherService2, and to place them on an interface. This makes mocking for testing much easier and keeps related concepts together (ideally in their own jars/modules).
I haven't come across such pattern before (one service containing other services).
What I commonly seen and used is something like below -
*SpecificController1 --> SpecificService1 --> SpecificDao1
SpecificController2 --> SpecificService2 --> SpecificDao2
Now, if SpecificService1 needs some functionality already available in SpecificService2, only then it will refer to SpecificService2.
So, I have few questions about the pattern described above:
How the MasterService would be used? i.e. any controller (or anyone) requiring any service would first use MasterService to get a reference to the actual service or MasterService would act as a delegate?
In what scenario, do you need such design and what are the advantages?

#autowired vs new key?

What is the difference using #Autowired annotation and new key ?
Let's within a class what would be the difference between :
#Autowired private UserDao userdao;
and
private UserDao userDao = new UserDaoImpl();
Is there an impact on the performance?
Besides low coupling, that others have already touched on, a major difference is that with the new approach, you get a new object every time, whether you want to or not. Even if UserDaoImpl is reusable, stateless and threadsafe (which DAO classes should strive to be) you will still create new instances of them at every place they are needed.
This may not be a huge issue at first, but consider as the object graph grows - the UserDaoImpl perhaps needs a Hibernate session, which needs a DataSource, which needs a JDBC connection - it quickly becomes a lot of objects that has to be created and initialized over and over again. When you rely on new in your code, you are also spreading out initialization logic over a whole bunch of places. Like in this example, you need to have code in your UserDaoImpl to open a JDBC connection with the proper parameters, but all other DAO classes have to do the same thing.
And here is where Inversion-of-Control (IoC) comes in. It aims to address just these things, by decoupling object creation and life-cycle from object binding and usage. The most basic application of IoC is a simple Factory class. A more sophisticated approach is Dependency Injection, such as Spring.
Is there an impact on the performance?
Yes, but it's most likely not going to be very significant. Using Springs dependency injection costs a little more in startup-time as the container has to be initialized and all managed objects set up. However, since you won't be creating new instances of your managed objects (assuming that is how you design them), you'll gain some runtime performance from less GC load and less object creation.
Your big gain however is going to be in maintainability and robustness of your application.
The above comments are correct, but here I am going add some example that helps to you.
Look We have 100 Classes that uses UserDao class, And you get dao instance like that:
private UserDao userDao = new UserDaoImpl(); in 100 places,
After few weeks the requirement changed and we need to use LdapUserDao or something similar
class LdapUserDao implements UserDao{
}
that implements UserDao. What do you do? How do you handle your new keywords, You tied impl class into usage.
If you use #Autowired in 100 places then from one place (if you use xml based config then, just go xml and switch to another UserDao from xml, if annotation the go to that component and switch Spring annotation to proper one) manage it, so in 100 places it appears. This is what is called DI pattern. This is whole purpose of DI
Another important thing is with spring annotation even you can manage object scope, but with new keyword no way(unles you do dumb singleton or something like that),
I am sure with new keyword you can no have
Prototype
Request
Single
Scoped objects
In terms of performance, It is quite difficult to say, unless to see your code. But I am sure at worst case they may have equal performance, otherwise springs way is fast, because As I know dao class should be singleton, not prototype, so whole project you will have on userdao object in spring way, with new way It depends where you are loosing reference to dao object. But Leave the performance. Do not consider performance over good design. All time 1st make it in good manner(not fast manner) with good design, then look it's performance.
You will get NullPointerException if you use
private UserDao userDao = new UserDaoImpl();
because it doesn't set the session reference that was declared in the *context.xml.
At runtime, you'll get a UserDaoImpl instance asigned in the userdao attribute in both cases.
But the first approach implies the ussage of the Dependency Injection pattern, that has some advantages over the second approach:
Your class now depends on an Interface, so it can work with any implementation of UserDao (maybe one that uses and RDBMS, other that uses XML files as a repository)
As you depend on an Interface now, Unit Testing and Mocking are pretty easy and straightforward.
Low-coupling is nice attribute to have in your code.
So you should prefer the second approach over the first, specially if your already using Spring (that's the idea behind an Inversion-Of-Control container)

Confused about Spring-Data DDD repository pattern

I don't know so much about DDD repository pattern but the implementation in Spring is confusion me.
public interface PersonRepository extends JpaRepository<Person, Long> { … }
As the interface extends JpaRepository (or MongoDBRepository...), if you change from one db to another, you have to change the interface as well.
For me an interface is there to provide some abstraction, but here it's not so much abstract...
Do you know why Spring-Data works like that?
You are right, an Interface is an abstraction about something that works equals for all implementing classes, from an outside point of view.
And that is exactly what happens here:
JpaRepository is a common view of all your JPA Repositories (for all the different Entities), while MongoDBRepository is the same for all MongoDB Entities.
But JpaRepository and MongoDBRepository have nothing in common, except the stuff that is defined in there common super Interfaces:
org.springframework.data.repository.PagingAndSortingRepository
org.springframework.data.repository.Repository
So for me it looks normal.
If you use the classes that implement your Repository then use PagingAndSortingRepository or Repository if you want to be able to switch from an JPA implementation to an Document based implementation (sorry but I can not imagine such a use case - anyway). And of course your Repository implementation should implement the correct interface (JpaRepository, MongoDBRepository) depending on what it is.
The reasoning behind this is pretty clearly stated in this blog post http://blog.springsource.com/2011/02/10/getting-started-with-spring-data-jpa/.
Defining this interface serves two purposes: First, by extending JpaRepository we get a bunch of generic CRUD methods into our type that allows saving Accounts, deleting them and so on. Second, this will allow the Spring Data JPA repository infrastructure to scan the classpath for this interface and create a Spring bean for it.
If you do not trust sources so close to the source (pun intended) it might be a good idea to read this post as well http://www.brucephillips.name/blog/index.cfm/2011/3/25/Using-Spring-Data-JPA-To-Reduced-Data-Access-Coding.
What I did not need to code is an implementation of the PersonRepository interface. Spring will create an implementation of this interface and make a PersonRepository bean available to be autowired into my Service class. The PersonRepository bean will have all the standard CRUD methods (which will be transactional) and return Person objects or collection of Person objects. So by using Spring Data JPA, I've saved writing my own implementation class.
Until M2 of Spring Data we required users to extend JpaRepository due to the following reasons:
The classpath scanning infrastructure only picked up interfaces extending that interface as one might use Spring Data JPA and Spring Data Mongo in parallel and have both of them pointed to the very same package it would not be clear which store to create the proxy for. However since RC1 we simply leave that burden to the developer as we think it's a rather exotic case and the benefit of just using Repository, CrudRepository or the like outweights the effort you have to take in the just described corner case. You can use exclude and include elements in the namespace to gain finer-grained control over this.
Until M2 we had transactionality applied to the CRUD methods by redeclaring the CRUD methods and annotating them with #Transactional. This decision in turn was driven by the algorithm AnnotationTransactionAttributeSource uses to find transaction configuration. As we wanted to provide the user with the possibility to reconfigure transactions by just redeclaring a CRUD method in the concrete repository interface and applying #Transactional on it. For RC1 we decided to implement a custom TransactionAttributeSource to be able to move the annotations back to the repository CRUD implementation.
Long story short, here's what it boils down to:
As of RC1 there's no need to extend the store specific repository interface anymore, except you want to…
Use List-based access to findAll(…) instead of the Iterable-based one in the more core repository interfaces (allthough you could simply redeclare the relevant methods in a common base interface to return Lists as well)
You want to make use of the JPA-specific methods like saveAndFlush(…) and so on.
Generally you are much more flexible regarding the exposure of CRUD methods since RC1 as you can even only extend the Repository marker interface and selectively add the CRUD methods you want to expose. As the backing implementation will still implement all of the methods of PagingAndSortingRepository we can still route the calls to the instance:
public interface MyBaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
List<T> findAll();
T findOne(ID id);
}
public interface UserRepository extends MyBaseRepository<User, Long> {
List<T> findByUsername(String username);
}
In that example we define MyBaseRepository to only expose findAll() and findOne(…) (which will be routed into the instance implementing the CRUD methods) and the concrete repository adding a finder method to the two CRUD ones.
For more details on that topic please consult the reference documentation.

Resources