Is this good practice to mark service class with annotation #service and #repository , since I am doing most of my DB operations in my service class. Does spring treats them a singleton class or prototype?
It makes easier for Spring to target pointcuts with more specific annotations. So, you should code DB operations in DAO layer and annotate it with #Repository as it causes exceptions to be wrapped up as DataAccessExceptions. Also, coding related stuff in it's own layer give rise to code modularity and reuse.
Moreover using the specialized annotations help to clearly demarcate application layers, in a standard 3 tier application.
Does spring treats them a singleton class or prototype?
By default all beans are of Singleton scope in Spring. To make it serve as prototype you have to change the scope of bean.
Related
In a spring MVC app , by default all beans are singleton ,but what should be the standard scopes for below classes according to good programming practices:
1.DAO classes
2.Controller classes
3.DTO classes
4.Service classes
I have read that DAO and Controller classes should be singleton scoped and DTO classes should not be beans so not annotated, whenever required, DTO classes should be instantiated using "new".
What will be the scope of #Service classes ?
And Which classes will have the Request and Session scopes if none of the above classes are created in these 2 scopes?
First of all not classes, but Spring managed beans have a scope. Difference is that you can have classes in your application that you didn't configure to be managed by Spring (So for example you didn't provide #Component annotation)
For the Spring managed beans default scope is Singleton. That means Spring container will provide the same instance everytime you ask for that bean to be autowired.
You can change that default scope with for example #Scopeannotation. So to answer your question, all of the above mentioned choices would have default scope of singleton but you could changed that to be requestor sessionscope if you would like (only applicable in web applications though). You can read more about setting scopes here.
ps. DTO classes are usually not declared to be managed by Spring - letting Spring manage a simple data transfer object doesn't make much sense.
So basically two things to consider here. The 1st is that if a bean is required to be declared as a spring bean . It depends on if you need to use the spring features for this class such as #Transactional , #Async , #PreAuthorize , #Autowired (i.e dependency injection) , or ensure the bean has certain scope etc. If not , it is simpler not define it as a spring bean and simply create it by yourself.
So the following types of the classes are required to define them as spring bean in most cases:
DAO because most probably need to inject EntityManager or JdbcTemplate to it
Controller because it is a part of spring-mvc and you need to define it as a bean such that you can use #RequestMapping / #GetMapping / #PostMapping / #PutMapping / #DeletMapping / #PatchMapping etc. on its method.
Service class because you need to inject it into the controller and you need to use #Transactional to manage the DB transaction for its method.
For DTO , in most case you can create it by yourself since it is just a data container in nature and does not require to use any spring features.
The 2nd thing to consider is what scope does a bean should be. You mainly need to think about if an instance of that class is okay to be executed safely by multiple request (i.e thread) concurrently. If yes , you can simply use the default singleton scope. If not , you can think about if you want each HTTP request (i.e #RequestScope) or each HTTP session (i.e. #SessionScope) has their own instance of that class to work with. For example , if you are implementing some shopping cart , you most probably want that the HTTP session has their won instance of a shopping cart and so you should use #SessionScope for the shopping cart.
I am implementing some of my business logic in my facade layer (which does some calculations and makes calls to service layers etc). What is the recommended stereotype for this layer, similar to #Service on service layer ? I use #Component as of now. Is it worth creating a new annotation as I'm using the same pattern across multiple projects?
It depends on whether you need to implement some logic on all the facade methods. For example , suppose you need to apply an AOP aspect on all the facade methods , by making a new specific annotation for it , you can locate the correct facade methods and process them based on the presence of this new annotation rather than a hard-coded list.
The documentation also mentions it:
Therefore, you can annotate your component classes with #Component,
but, by annotating them with #Repository, #Service, or #Controller
instead, your classes are more properly suited for processing by tools
or associating with aspects. For example, these stereotype annotations
make ideal targets for pointcuts. #Repository, #Service, and
#Controller can also carry additional semantics in future releases of
the Spring Framework. Thus, if you are choosing between using
#Component or #Service for your service layer, #Service is clearly the
better choice. Similarly, as stated earlier, #Repository is already
supported as a marker for automatic exception translation in your
persistence layer.
Here as Spring needs to locate all repository classes to apply an automatic exception translation for them , so it creates a new specific annotation #Repository.
I have a spring-boot project. Some of the classes I am using it in the 'spring' way, meaning that they are annotated by "#Service", "#Repository", "#Autowired". At the same time, I have lots of classes, which are only used in the normal Java way, meaning that there are no any Spring annotations, and they are created in the standard way of constructing an object in a constructor.
For example, one of the non-annotated classes is:
public class GenericTree<T>
{
private GenericTreeNode<T> root;
public GenericTree ()
{
root = null;
}
public GenericTreeNode<T> getRoot ()
{
return this.root;
}
public void setRoot (GenericTreeNode<T> root)
{
this.root = root;
}
...
}
Is it OK or normal to have a mixure of classes with or without Spring annotations? Probably, I could convert all non-annotated classes into annotated classes by using Spring's annotation markers. Does that really benefit or is it necessary?
BTW, my application's main logic and functions are not web-centric, although they are created as a Spring project. The reason I created in Spring is I want to provide a restful service for my interface so that I can easily test in browser in development, and others can use it with Restful service.
Yes it is ok.
Keep in mind that annotations are not Spring exclusive. Annotations were introduced in Java 5 and they are just meta data for your Java code. This meta data can be useful at:
Compile time
Build time
Runtime
You can even create your own custom annotations and annotate your code with them.
Spring framework comes with some annotations and each one of them has its purpose, but that doesn't mean you have to annotate all your classes with Spring annotations when you are using this framework.
When you annotate your classes as Spring Beans, they become part of the Spring Application Context, thus making them available to be injected with the #Autowired annotation (Spring framework is based on the dependency injection design pattern). But Spring annotations have other implications too, I cannot go into the detail of each one of them but for example, you have to consider that the default scope of annotations like #Bean, #Component, #Controller, #Repository, #Service is Singleton. So whenever you annotate a class with one of these annotations and you don't define a scope, what you get is a singleton class shared all over your application. Other scopes are:
singleton
prototype
request
session
application
websocket
Taking in consideration your GenericTree class, does it make sense to annotate an abstract data structure class as a Spring Bean? Probably not.
So yes, when you develop an application based on Spring framework the normal thing is to have a mixture of Spring annotated classes and regular POJO's.
I recommend you to read the Spring framework documentation, learn what dependency injection is and the purpose and implications of the most used Spring annotations.
what if i don't annotate DAO classes with #Repository, will that still makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException?? Can anyone expain this? bit confused with #Repository annotation
Definition of #Repository given on this link
Indicates that an annotated class is a "Repository", originally
defined by Domain-Driven Design (Evans, 2003) as "a mechanism for
encapsulating storage, retrieval, and search behavior which emulates a
collection of objects".
Teams implementing traditional J2EE patterns such as "Data Access
Object" may also apply this stereotype to DAO classes, though care
should be taken to understand the distinction between Data Access
Object and DDD-style repositories before doing so. This annotation is
a general-purpose stereotype and individual teams may narrow their
semantics and use as appropriate.
A class thus annotated is eligible for Spring DataAccessException
translation when used in conjunction with a
PersistenceExceptionTranslationPostProcessor. The annotated class is
also clarified as to its role in the overall application architecture
for the purpose of tooling, aspects, etc.
what if I don't annotate DAO classes with #Repository, will that still
makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException??
No,Because as per details given on this link
Bean post-processor that automatically applies persistence exception
translation to any bean marked with Spring's #Repository annotation,
adding a corresponding PersistenceExceptionTranslationAdvisor to the
exposed proxy (either an existing AOP proxy or a newly generated proxy
that implements all of the target's interfaces).
Hope this will help you understand!!
I started my first web project using JSF, Hibernate and Spring and I would like to know if the architecture that I designed is the most appropriate.
The beans are annotated with #Controller, and the InventoryServiceImpl is annotated with #Service. I also use #Autowired for dependency injection. The AbstractDao has the Hibernate's SessionFactory attribute (it's not ServiceFactory as it says in the image, sorry about that) which is responsible for the access to the database itself, so the DAO's Implementations just calls methods of the AbstractDao superclass.
My concern is mainly regarding the Service, as I am not sure if only one class that accesses all DAOs is the wisest thing to do.
The UML diagram:
uml-diagram http://imagizer.imageshack.us/v2/1280x1024q90/673/ebfa7f.png
Any comments or suggestions are highly appreciated.