Spring Framework for Beginners

Spring Framework 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 Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC, etc.
    If you want to develop the High-performance large scale distributed enterprise application. As J2EE Architect, suggest the best technologies and frameworks for application architecture.

SERVICES TECHNOLOGIES & FRAMEWORKS (without Spring) INTRODUCED IN SPRING TO INTEGRATE WITH
Web Support Servlets, JSP, Struts, JSF, Struts 2, Flex Spring MVC All
Persistence Service JDBC, Hibernate, JPA, Entity Bean(EJB) All
Transaction Service JDBC Transaction, Hibernate Transaction,

JPA Transaction,

EJB Container

Spring Transaction
Security Service JAAS, Third party Spring Security All
Remoting Service RMI, EJB 2/3, Web Services All
Timer Service JDK, EJB Container
Messaging Service JMS, MDB All
Resource Management Web Container,

EJB Container

Spring Container
Life Cycle Management Web Container,

EJB Container

Spring Container
Mailing Service Java Mail API All
Registry Service RMI Registry,

JNDI Registry,

UDDI

All
Logging Service Log4J
Unit Testing Junit, Mock Objects,

Easy Mock

All
IOC EJB3 Container Spring Container
AOP EJB3 Container Spring Container
Mobile Support J2ME, iPhone, Android, Windows phone 7, etc Spring integration with android
Big Data Support Hadoop Spring Integration with Hadoop

Spring architecture
Spring framework provides a number of features for an enterprise application. However, it does not enforce the developers to integrate their application with the complete framework. The various features provided by the Spring framework are categorized into seven different modules. Developers may choose to integrate their application with one or more Spring modules depending upon the features they want to use in their application.

Core container: The core container is the heart of the Spring framework and all other modules are built on top of it. It provides the dependency injection feature, also is known as inversion of control. This module contains the BeanFactory (an implementation of factory pattern) which creates and manages the life cycle of the various application objects (known as beans) defined in the Spring bean configuration file.

Application context: This module provides various enterprise level services internationalisation (i18n), scheduling, JNDI access, email etc.

AOP: This module helps in implementing the various cross-cutting concerns in the application like logging, transaction management, etc. These concerns are decoupled from the application code and are injected into the various point cuts through the configuration file.

Spring web: Spring framework helps in developing a web-based application by providing the Spring web module. This module is built on top of application context module and provides web-oriented features.

Spring MVC: Spring MVC module is built on top of Spring web module and helps in developing a web application based on MVC design pattern.

Spring DAO: Almost every enterprise application needs to interact with the database. Spring DAO module makes it easy to interact with the database by providing an abstraction over low-level JDBC tasks like creating a database connection, release it, etc.

Spring ORM: There exist a number of popular object-relational mapping tools like Hibernate, iBatis, JPA, etc. Spring ORM module helps in integrating with these tools.

Advantages of the Spring Framework:

  • The Spring Framework is lightweight in nature due to its POJO implementation, which doesn’t force us to inherit any class or implement any interfaces.
  • TIt supports other frameworks and its integration makes Spring easier to develop.
  • The Spring application is loosely coupled due to the Dependency Injection.
  • It is easier to test, and it doesn’t require any server to run the application.
  • It provides a powerful abstraction to JavaEE Specifications, like JDBC, JTA, etc.

Disadvantages of Spring Framework:

  • The learning curve for Spring Framework is very high as most developers find it hard to understand and apply.
  • The nature of the Spring Framework keeps changing over the course of time, which makes it harder to grasp. For example, the annotation-based Spring is not everybody’s cup of tea.
  • For many, it’s a time-consuming process, as the Spring Framework has lots of integration with another framework, due to which it is hard to know all the options that are available.

 Spring IOC (Inversion of Control)
when you are developing any component or bean, it may contain some dependencies. Those bean dependencies can be initialized in two ways:

  • Create the object and initialize
  • Lookup the registry and initialize.

With Spring IOC or DI (Dependency Injection), Spring Container is responsible for initializing or injecting bean dependencies automatically.

Without Spring IOC With Spring IOC
Class A
{
Void m1()
{
…….
}
}
Class B
{
Void m2()
{
……
}
Class Hello
{
A aobj=null;
B bobj=null;
public Hello()
{
Aobj= new A();
Bobj=ctx.lookup(“B-JNDI”);
}void show()
{
Aobj.m1();
Bobj.m2();
}
}
Class A
{
Void m1()
{
…….
}
}
Class B
{
Void m2()
{
……
}
Class Hello
{
@AutoWired
A aobj=null;
@Resource
B bobj=null;
Void show()
{
Aobj.m1();
Bobj.m2();
}
}

Note: Every class you are wtiing in Spring application can be called as Spring Bean.

  • Hello bean needs A object and B object.
  • Hello bean needs A resource and B resource.
  • Hello bean needs A bean and B bean
  • Hello bean is depending on two beans called A bean and B bean.
  • Hello bean dependencies called A and B has to initialize.
  • Hello bean dependencies called A and B has to be injected.

With Spring IOC, Spring container injects the Hello Bean dependencies called A and B. Spring Dependency injection uses three ways to inject the dependencies.

  1. Setter Injection
  2. Constructor Injection
  3. Field Injection (Using Annotations)

Example:

Class Student
{
String sid;       // 1. Setter Injection
String sname; // 2. Constructor Injection
@Autowired
Address add;  // Field Injection (using Annotations)
public void setSid(String sid)
{
This.sid=sid;
}

public Student(String sname)
{
This.sname=sname; // 2 Constructor Injection
}
}

First Spring Example Setup in Eclipse

  1. Create the java project with the name: xadmin
  2. Add all the Spring jars to project build path.
  3. Copy Spring Configuration document to src folder. Xadmin.xml file (default is application context.xml)
  4. Create a package called com.xadmin.spring and write the following:
  • A.java
  • B.java
  • Hello.java
  • xadmin.java

5. Update the Spring configuration Document.

  • Xadmin.xml

File required for the example:

  1. Xadmin.java
  2. A.java
  3. B.java
  4. Hello.java
  5. Xadmin.xml

Xadmin.java

package com.xadmin.spring;
Import org.springframework.context.ApplicationContext;
Import org.springframework.context.support.classPathxamlApplicationContext;

public class Xadmin
{
public static void main( String[] args)
{
/*
// without IOC

A aobj= new A();
aobj.seta(99);
aobj.setMsg(“HelloGuys”);
B bobj= new B(88, “Hai Guys”);
Hello hello= new Hello(bobj);
Hello.setAobj(aobj);

// hello.show();

*/

ApplicationContext ctx=new ClasspathxmlApplicationContext(“Xadmin.xml”);
System.out.println(“Spring container is Ready”);
System.out.println(“........);
Hello h=(Hello) ctx.getBean(“hello”);
show();
}
}

A.java

Package com.xadmin.spring;

public class A 
{
private int a;
private String msg;	

public A()
{
System.out.println(“A-D-C”);
}

public void seta(int a)
{
System.out.println(“A-setA()”);
This.a=a;
}

public void setMsg(String msg)
{
System.out.println(“A-setMsg()”);
This.msg=msg;
}

public void showA()
{
System.out.println(“A-show A()”);
System.out.println(a);
System.out.println(msg);
}
}

B.java

package com.xadmin.jtcindia.spring;

public class B
{
private int b;
private String str;

public B(int b, String str)\
{
System.out.println(“B-2 arg”);
This.b=b;
This.str=str;

public void showB()
{
System.out.println(“B-showmB()”);
System.out.println(b);
System.out.println(str);
}
}
}

Hello.java
Package com.jtcindia.spring;

public class Hello
{
Private A aobj;
Private B bobj;
public void setAobj(A aobj)
{
System.out.println(“Hello-setAobj”);
This.bobj=bobj;
}

Public void show()
{
Aobj.showA();
Bobj.showB();
}
}

Xadmin.xml

<bean id=”aobj” class=”com.xadmin.spring.A”>
<property name=”a” value=”99”/>
<property name=”msg” value=”Hello Guys”/>
</bean>

<bean id=”bobj” class=”com.xadmin.spring.B”>
<constructor-args value=”88”/>
<constructor-arg value=”Hai Guys”/>
</bean>
<bean id=”hello” class=”com.jtcindia.spring.Hello”>
<property name=”aobj” ref=”aobj”/>
<constructor-arg ref=”bobj”/>
</bean>
</beans>

Here, Spring container is doing

  1. Spring container is creating the resources.
  2. It is initializing the resources.
  3. It is using the Singleton pattern.
  4. It is using a Factory pattern.

An Important Interview Questions and Answers for the beginners

Q1 What is a Spring Bean?
Ans: Every class you are writing in spring application can be called as Spring Bean.

Q2 What is Dependency?
Ans: Any property available in a Bean class which needs to be initialized is called as Dependency.

Q3 What is Injection?
Ans: Initialization of Bean class property is also called as Injection.

Q4 What is Dependency Injection (DI)?
Ans: The process of initializing Bean dependencies is called Dependency Injection.

Q5 What are the types of Dependency Injection supported by Spring?
Ans: Spring Dependency Injection uses 3 ways to inject the dependencies.

  1. Setter Injection
  2. Constructor injection
  3. Field Injection. ( using Annotations)

Q6 What is Setter Injection?
Ans: The process of initializing Bean Dependencies with setter methods is called as setter Injection.

Q7 How can I implement Setter Injection?
Ans: Using <property> tag.

Q8 What is Constructor Injection?
Ans: The process of initializing Bean Dependencies with Constructor is called as Constructor Injection.

Q9 How can I implement Constructor Injection?
Ans: Using <constructor-arg> tag.

Q10 What is Bean Definition?
Ans: Configuring Bean and its dependencies in Spring Configuration Document is called as Bean Definition.

Q11 When should i use <property> tag and <constructor-arg> tag?
Ans: <property> tag is use for setter Injection
<constructor-arg> tag is use for constructor Injection.

Q12 When should you use value attribute and ref attribute?
Ans: Use value attribute for specifying values for a simple type of variables like

  • Primitive variables
  • wrapper variables
  • String variables

Use of ref attribute for specifying bean references for reference type variables.

Q13 What are the GOF patterns used in Spring IOC container?
Ans: Single-ton pattern and Factory pattern

Q14 What is Spring container?
Ans: ApplicationContext object is called a Spring Container.

Q15 What will be done by the spring container when it finds the following bean defination?
<bean id=”aobj” class=”com.xadmin.spring.A”>
<property name=”a” value=”99”/>
<property name=”msg” value=”Hello Guys”/>
<bean>
Ans: A aobj= new A();
aobj.setA(99);
aobj.setMsg(“HelloGuys”);

Q16 What will be done by the spring container when it finds the following bean defination?
<bean id=”bobj” class=”com.xadmin.spring.B”>
<constructor-arg value=”88”/>
<constructor-arg value=”Hello Guys”/>
<bean>
Ans: B bobj= new B(88,”Hai Guys”);

Q17 What will be done by the spring container when it finds the following bean defination?
<bean id=”hello” class=”com.xadmin.spring.Hello”>
<property name=”aobj” ref=”aobj”/>
<constructor-arg ref=”bobj”/>
<bean>
Ans: Hello hello= new Hello(bobj);
Hello.setAobj(aobj);

Q18 What is spring configuration file?
Ans: Spring configuration file is an XML file which contains various bean definitions.

Q19 What will happen with the following code?
 <beans>
<bean id=”hello” class=”com.xadmin.spring.hello”/>
</beans>
Hello hello= (Hello) ctx.getbean(“hello1”);
Ans: Exception will be raised
NoSuchBeanDefinationException:NO Bean named ‘hello1’ is defined

Q20 Can i configure two beans with same id?
<beans>
<bean id=”hello” class=”com.xadmin.spring.Hello1”/>
<bean id=”hello” class=”com.xadmin.spring.Hello2”/>
<beans>
Ans: No, Bean id must be unique. There are multiple occurrences of Id value ‘hello’.

Q21 Can I configure two beans with the same Bean class?
Ans: Yes, we can configure it.
ie.
<beans>
<bean id=”hello1” class=”com.xadmin.spring.Hello”/>
<bean id=”hello2” class=”com.xadmin.spring.Hello”/>
<beans>
Hello h1=(Hello) ctx.getBean(“hello1”);
Hello h2=(Hello) ctx.getBean(“hello2”);
Here, h1 != h2

Q22 What will happen with the following code?
<beans>
<bean id=”hello1” class=”com.xadmin.spring.Hello”/>
<constructor-arg value=”99”/>
<bean>
<beans>
Class Hello
{
int x;
//No constructor
}

Ans: BeanCreationException: Error creating bean with name ‘hello’ defined in class path resource xadmin.xml could not resolve matching constructor.

Q23 What will happen with the following code?
<beans>
<bean id=”hello” class=”com.xadmin.spring.Hello”/>
<property name=”x” value=”99”/>
<beans>
Class Hello
{
int x=10;
// No setter
}
Ans: Not writable property exception: Invalid property ‘x’ of bean class [A]: bean propert ‘x’ is not writable or has an invalid setter method.

Conclusion:
In this article, we have learned about the Spring framework, its architecture, main features, its advantage, and its disadvantages. We have learned how the Spring framework helps us develop loosely coupled applications using dependency injection where the dependant objects are injected using a configuration file. We also learned about the Spring IOC (Inversion of Control) with a fully functional example. Please, feel free to drop a comment in the comment box if you find any doubt regarding the topic or you want to share more information about the topic.

 

Leave a Reply

Your email address will not be published. Required fields are marked *