Thursday, 4 January 2018

Spring Framework Topics - JEE

I am writing this blog just to verify the concepts of Spring :

Spring MVC is one of the well know framework to develop Web applications. There are lot of enhancements which are done to Spring MVC V3.0, like Spring Boot, Spring Cloud, Spring V4.0 and it's completely open source for developing Enterprise applications.

The important concepts in Spring are :

  • Spring Context : For dependency injection(DI)
  • Spring DAO : For database operation using DAO Pattern
  • Spring JDBC : Foor JDBC and Datasource support
  • Spring ORM : For ORM Tool support such as Hibernate
  • Spring AOP: For Aspect Oriented Programming 
  • Spring Web module: For creating web application.

Advantages of Spring Framework:

Light weight : Spring is light weight, basic version of Spring is 2 MB.
DI/IOC : This helps to achieve loose coupling by wiring independent components/objects.
Spring Container : contains and manages life cycle of application
Transaction Management : Spring Supports transaction management, i.e, JDBC, File upload, Exception handling ..etc.either by spring annotation or bean configuration.
Exception Handling : Spring provide convenient API to translate technology specific exceptions  (thrown  by JDBC, Hibernate..etc.) in to consistent unchecked exceptions.
Aspect-Oriented Programming : AOP breaks program part in to distinct parts (called concerns). It's used to increase modularity by cross-cutting techniques.A cross cutting concern is a concern that can affect the whole application and should be centralized in one location in code as possible, such as transaction management , authentication, logging, security ..etc.

Spring Bean: 

Any normal Java class that is initialized by Spring IOC container is called Spring Bean. We use Spring application context to get Spring Bean instance. Spring IOC Container manages the lifecycle of Spring Bean Scope and injecting any required dependencies in the bean.

Different scopes of Spring bean:

When we declare <bean>, we can specify scope of the bean to inform the IOC container about the creation of the bean and how long it will survive.
For any Java application there are two different scopes called Singleton and Prototype.
There are three different scopes i.e. request, session and global-session specifically for Spring based Java web applications.
  • Singleton is the default scope of any bean. This means a single instance of the bean will get created per IOC Container. Hence the Singleton beans are not thread safe.
  • In Prototype scope a new instance will get created every time the bean is requested.
  • In request scope, a bean is defined to an HTTP request, This scope is valid only in a web-aware spring ApplicationContext.
  • In Session scope, a bean is defined to an HTTP session. This Scope is valid only in a web-aware Spring ApplicationContext.
  • In global-session scope, a bean is defined to a global HTTP session. This scope is valid only in a web-aware spring ApplicationContext.


To set the scope of the spring bean, we can use scope attribute in <bean> tag. @Scope is used in annotation based DI.


Spring IoC Container :

The Spring Container is at the core of the Spring framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till descrution. The Spring container uses dependency injection(DI) to manage the componenets that make up an application.

There are two different types of applications:
  • BeanFactory Container : This is the heart of the Spring Container. org.springframework.beans.factory.BeanFactory is an interface and acts as a IoC Container which instantiates, Configures, and manages a number of beans.
  • ApplicationContext container: org.springframework.context.ApplicationContext interface also acts as the IoC Container but the ApplicationContext interfaceis builf on top of the BeanFactory interface to provides some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for l18N), event propogation application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.
For annotation based dependency injection, @Autowired annotation is used. The Classes marked with @Component /@Service / @Repository etc can be injected to the property which is marked with @Autowired

@Autowired is applied to 
  • field : for the filed-based dependency injection
  • setter for the setter dependency injection. Same as field-based dependency injection.
  • constructor for constructor-based dependency injection
Difference between constructor based and setter based DI : 
  • Injection of dependencies can be optional or mandatory. For Mandatory injection we use constructor based DI. While for the optional dependencies we can use setter based DI. However, we can mark a setter based DI with @Required annotation.
  • In case of cyclic dependency, constructor based DI won't be able to inject but setter based DI would be able to inject
  • If more number of parameters to be injected then it is advisable to use constructor based DI
Difference between context:annotation-config and context: component-scan:

context:annotation-config is used to activate annotations in beans already registered in the application context. context:component-scan can also do what context:annotation-config does but also scans packages to find and register beans within the application context.

Difference between @Component, @Controller, @Repository & @Service annotations

If a class is marked with @Component/@Controller/@Service/@Repository annotation then the spring DI container can identify the class during component scan mechanism. However, it is good idea to use @Service for service layer classes and @Controller should be used in spring MVC web controller.@Repository is used to import DAOs in to DI container. Also any unchecked exception will get translated into Spring DataAccessException.

ViewResolver vs MultipartResolver:

ViewResolver is used to resolve view by name. This interface is implemented by InternalResourceViewResolver MultipartResolver is used to handle file upload in web application.

Validation in Spring MVC:

org.springframework.validation.Validator interface supports spring MVC validation. Some of the util methods to validate a form are rejectIfEmptyOrWhitespace() and rejectIfEmpty() in the ValidationUtils class.

Example : 

@Component public class EmployeeValidator implements Validator { public boolean supports(Class clazz) { return EmployeeVO.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.firstName", "First name is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.lastName", "Last name is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email", "Email is required."); } }


Another approach to validate form in Spring MVC is:
  • Use Hibernate Validations (Eg; @NotNull, @Size etc) for the properties of the model bean
  • Use @Valid, BindingResult in the method signature of the controller.
  • BindingResult.hasErrors() methods to validate the model bean.
Spring MVC interceptor:

HandleInterceptor interface acts as a spring MVC interceptor. It intercepts before and after serving the request. preHandle(), postHandle() and afterCompletion() are the methods to be overridden in case you implement HandlerInterceptor interface. However, to avoid overriding, you can use HandleInterceptorAdapter class.

Difference between Spring DAO and Spring ORM:

DAO is a design pattern to minimize coupling between the application and the backend ORM deals with how to map objects in to an object relation database which reduces coupling between the database and application.
If you use ORM without DAO then your application will become ORM dependent so it would be hard to move from One ORM (say hibernate ) to another ORM (e.g. NoSQL).

Spring DAO implemented using @Repository annotation. Spring repository extends JPARepository and passes JPA entity and its primary key.

No comments:

Post a Comment