Advanced

About Spring

Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc. The framework, in broader sense, can be defined as a structure where we find solution of the various technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc
1. Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is around 2MB.
2. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform.
3. Benefits of Spring
 a. Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product 
 b. Spring is organized in a modular fashion.
 c. makes use of existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view technologies.
 d. by using JavaBeanstyle POJOs, it becomes easier to use dependency injection for injecting test data
 e. Spring's web framework is a well-designed web MVC framework
 f. Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions
 g. Lightweight IoC containers tend to be lightweight, This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.
 h. Spring provides a consistent transaction management interface, which can scale up and down as per requirement.

Spring Modules

The Spring Framework provides about 20 modules which can be used based on an application requirement.

spring

 

How Spring Operates

spring

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 destruction. The Spring container uses DI(dependency Injection) to manage the components that make up an application, These objects are called Spring Beans.
 The IOC container uses either of the 3 files to represent the configuration files
 a. XML file, 
 b. Java annotations, or 
 c. Java code.
 
Spring IoC container makes use of Java POJO(plain old java object) classes and configuration metadata to produce a fully configured and executable system or application.

Types of Containers

a. Spring BeanFactory Container
 is defined by the org.springframework.beans.factory.BeanFactory interface.
 
 b. Spring ApplicationContext Container
 is defined by the org.springframework.context.ApplicationContext interface

Spring BeanFactory Container
This is the simplest container providing the basic support for DI. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring.

Spring ApplicationContext Container
This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.

NOTE:
The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications where data volume and speed is significant.

 

Bean Definition and its importance

Bean definition contains the information called configuration metadata, which is needed for the container to know the following −
 a. How to create a bean
 b. Bean's lifecycle details
 c. Bean's dependencies

All the above configuration metadata translates into a set of the following properties that make up each bean definition
 a. class
 b. name
 c. scope
 d. constructor-arg
 e. properties
 f. autowiring-mode
 g. lazy-initialization mode
 h. initialization method
 i. destruction method

 

Sample of XML-based configuration file with different bean definitions including lazy initialization, initialization method, and destruction method −

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- A simple bean definition -->
   <bean id = "..." class = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with lazy init set on -->
   <bean id = "..." class = "..." lazy-init = "true">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with initialization method -->
   <bean id = "..." class = "..." init-method = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with destruction method -->
   <bean id = "..." class = "..." destroy-method = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- more bean definitions go here -->
   
</beans>

 

Bean Scope

1. singleton
This scopes the bean definition to a single instance per Spring IoC container (default).
2. prototype
This scopes a single bean definition to have any number of object instances.
3. request
This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
4. session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
5. global-session
This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

 

Some Examples of Bean Scope

a. Singleton

<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
   <!-- collaborators and configuration for this bean go here -->
</bean>

b. prototype

<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
   <!-- collaborators and configuration for this bean go here -->
</bean>

Dependency Injection in Spring

Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled
In such case we provide the information from the external source such as XML file. It makes our code loosely coupled and easier for testing.

 

Spring provides two ways to inject dependency

1. By Constructor
2. By Setter method
Like Constructor Injection, we can inject the dependency of another bean using setters. In such case, we use property element.

 

Difference between constructor and setter injection

There are many key differences between constructor injection and setter injection.

1. Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by setter method only.

2. Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection.

3. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like constructor. So setter injection is flexible than constructor injection.

 

Dependency Injection using Constructor arguments

We use <constructor-arg value="XXXXXX"></constructor-arg> tag for as constructor argument in Beans.xml file for setting values based on constructors

Bean

<bean id="a1" class="com.sauravcodeblog.Address"> 
<constructor-arg value="ghaziabad"></constructor-arg> 
<constructor-arg value="UP"></constructor-arg> 
<constructor-arg value="India"></constructor-arg> 
</bean>

CONSTRUCTOR

public Address(String city, String state, String country) { 
 super(); 
 this.city = city; 
 this.state = state; 
 this.country = country; 
}

 

Dependency Injection using Setters

we use <property name="name" value="XXXXXXX"></property> tag in Beans.xml file for setting values based on setters

Bean

<bean id="q" class="com.sauravcodeblog.Question"> 
<property name="id" value="1"></property> 
<property name="name" value="What is Java?"></property> 
<property name="answers"> 
<list> 
<value>Java is a programming language</value> 
<value>Java is a platform</value> 
<value>Java is an Island</value> 
</list> 
</property> 
</bean>

Getters-Setters

public class Question { 
private int id; 
private String name; 
private Map<Answer,User> answers;

public int getId() {
 return id;
}

public void setId(int id) {
 this.id = id;
}

public String getName() {
 return name;
}

public void setName(String name) {
 this.name = name;
}

public Map<Answer, User> getAnswers() {
 return answers;
}

public void setAnswers(Map<Answer, User> answers) {
 this.answers = answers;
}

 

Importance of ‘ref’ keyword in Spring

If we have dependent object in the collection, we can inject these information by using the ref element inside the list, set or map

 

AUTOWIRING

Autowiring in Spring
1. Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection.
2. Autowiring can't be used to inject primitive and string values. It works with reference only.

Advantage of Autowiring
1. It requires the less code because we don't need to write the code to inject the dependency explicitly.

Disadvantage of Autowiring
1. No control of programmer.
2. It can't be used for primitive and string values.

Autowiring Modes
There are many autowiring modes:
1. no : It is the default autowiring mode. It means no autowiring bydefault.
2. byName : The byName mode injects the object dependency according to name of the bean. In such case, property name and bean name must be same. It internally calls setter method.
3. byType : The byType mode injects the object dependency according to type. So property name and bean name can be different. It internally calls setter method.
4. constructor : The constructor mode injects the dependency by calling the constructor of the class. It calls the constructor having large number of parameters.
5. autodetect : It is deprecated since Spring 3. Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

Simple Example
<bean id="a" class="com.sauravcodeblog.className" autowire="byName"></bean>
class="PackageName.className"

Limitations with autowiring
Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions

Limitations & Description
1. Overriding possibility : You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
2. Primitive data types : You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
3. Confusing nature : Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring.

 

Bean’s Life Cycle with Initialization callbacks and Destruction callbacks

Initialization callbacks
The org.springframework.beans.factory.InitializingBean interface specifies a single method − void afterPropertiesSet() throws Exception;
Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows −

public class ExampleBean implements InitializingBean {
 public void afterPropertiesSet() {
 // do some initialization work
 }
}

in your beans.xml file, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example −

<bean id = "exampleBean" class = "PackageName.ExampleBean" init-method = "myInitFunc"/>

Following is the class definition −
public class ExampleBean {
 public void myInitFunc() {
 // do some initialization work
 }
}
Destruction callbacks
The org.springframework.beans.factory.DisposableBean interface specifies a single method − void destroy() throws Exception;
Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows −

public class ExampleBean implements DisposableBean {
 public void destroy() {
 // do some destruction work
 }
}

In your beans.xml file, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example −

<bean id = "exampleBean" class = "packageName.ExampleBean" destroy-method = "destroy"/>

Following is the class definition −
public class ExampleBean {
 public void destroy() {
 // do some destruction work
 }
}
Register a shutdown hook
If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released.

It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method.

public class MainApp {
 public static void main(String[] args) {
 AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
 obj.getMessage();
 context.registerShutdownHook();
 }
}

 

BeanPostProcessors

The BeanPostProcessors operate on bean (or object) instances, which means that the Spring IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their work.
You can configure multiple BeanPostProcessor interfaces and you can control the order in which these BeanPostProcessor interfaces execute by setting the order property provided the BeanPostProcessor implements the Ordered interface.

1. Include the AbstractApplicationContext using.
"AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");"
make sure you have imported - "import org.springframework.context.support.AbstractApplicationContext;"

2. Defile a class that implements BeanPostProcessor interface
public class SomeClassName implements BeanPostProcessor {
}

3. include the following in your class(SomeClassName)
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//Your codes here
 return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 //Your codes here
 return bean; // you can return any other object as well
}
//You can include other PostBeanProcess methods as well

4. include the bean
<bean class = "com.sauravcodeblog.InitHelloWorld" />

5. Register the shutdownHook, in your class from where you are initializing the beans.
ClassName classObj = (ClassName) context.getBean("beanID");
classObj.getMessage();
context.registerShutdownHook();

@Annotations

Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for properties wired through both approaches.
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, make sure you include the following



<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
 xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context = "http://www.springframework.org/schema/context"
 xsi:schemaLocation = "http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>
 <!-- bean definitions go here -->

</beans>

 

Annotations & its Description

1 @Required : This annotation applies to bean property setter methods.
2 @Autowired: This annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
3 @Qualifier: This annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
4 JSR-250 Annotations : Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.

 

Initial Setup and First Program

1. Setup Java Development Kit (JDK)
2. set PATH=C:\jdk1.6.0_15\bin;%PATH% 
3. Download the apache commons logging binaries from here -
 https://commons.apache.org/proper/commons-logging/download_logging.cgi 
4. download the https://repo.spring.io/release/org/springframework/spring/4.1.6.RELEASE/spring-framework-4.1.6.RELEASE-dist.zip
 file, and extract the file in any location.
5. You will find all the Spring libraries in the directory X:\Path\spring\libs. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application.
6. Create a sample java project(just like what we do in Core in java) - named HelloSpring
7. Add required libraries:
 right-click on your project name HelloSpring -> Properties(Alt+Enter -> Java Build Path -> Add Library -> User Library-> User Libraries -> New -> give a name (say, Spring) -> Add External jars -> Locate the jar files extracted in step 4 and 5 and apply it.
8. Create a new package. right click on src in package explorer section and follow the option − New → Package -> give a name (say, com.sauravcodeblog).
9. Next we will create HelloWorld.java and MainApp.java files under the com.sauravcodeblog package.
10. create a Bean Configuration file- Beans.xml in src directory of the package created in step 8.

11. Add the following in HelloWorld.java

package com.sauravcodeblog;
public class HelloWorld {
 private String message;

public void setMessage(String message){
 this.message = message;
 }
 public void getMessage(){
 System.out.println("Your Message : " + message);
 }
}

12. Add the following in MainApp.java
package com.sauravcodeblog;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
 public static void main(String[] args) {
 ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
 HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
 obj.getMessage();
 }
}

13. Add the following in Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
 xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation = "http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id = "helloWorld" class = "com.sauravcodeblog.HelloWorld">
 <property name = "message" value = "Hello World!"/>
 </bean>

</beans>

14. run the program.

Design a site like this with WordPress.com
Get started