Pages Navigation Menu

Coding is much easier than you think

Spring Environment Setup

Posted by on Aug 15, 2013 in Spring, Spring Tutorial | 0 comments

 
spring-tutorial
 
In this section, you will see about setting up Eclipse IDE to get started with our code development works, installing the latest JDK a, setting the environment variables and adding the required JARs for running of some basic Spring based applications.

 

Step 1. Download and install Eclipse IDE of your preference. For Eclipse IDE installation instructions, you can refer here.
eclipse IDE installation instructions

 

Step 2. Download the latest JDK, as per your system requirements from here

Step 3. Set the environment variables in your system

Right click on MyComputer -> Properties. On the left side pane, choose Advanced System Settings.
 
** UPDATE: Spring Complete tutorial now available here.
 

EclipseSetUp1

 

A window opens up. Choose Advanced tab on this and click on Environment Variables button

EclipseSetUp2

Environment Variable window opens up. In the system variables, select New.

EclipseSetUp3

Provide the  variable name – JdkHome(this name can differ)

variable value – C:Program FilesJavajdk1.7.0_11bin . The provided location is the path where the bin folder under JDK is present.

Click ok

EclipseSetUp m

Now your eclipse is well set.

 

Step 4 : Now that your Integrated Development Environment(IDE) is ready. Let us create a project.

Select File ->New->Java project

Provide an appropriate name.

NewProjSpring

 

Step 5 : Download the required JAR files. Find below the list of JAR files that will be made use of, over various stages of this tutorial.

Spring Basic jars

Step 6 : Right click on your project. Select Build path->Configure Build path.

eclipseSetUpBuildPath

On the libraries  tab, choose Add external libraries. Here browse and add the list of JARs downloaded as per the previous step. Click ok
EclipseSetUpExtJars

Thats it! You are now all set to start trying out hands-on exercises using spring !!

Advertisements
Read More

Spring Inversion Of Control

Posted by on Aug 15, 2013 in Spring, Spring Tutorial | 0 comments

 
spring-tutorial
 
One of the core concepts in Spring is Inversion Of Control(IOC). It makes use of  BeanFactory to manage Java objects from instantiation to destruction. The IOC implements Dependency Injection, thereby facilitating loose coupling between components(POJOs). When it comes to large codes, one of the main problems at hand would be the dependencies between the various classes. Typically high level modules depend on low level modules for their values/functionalities. Here, whenever a change is required we have to face the problem of

  1. Rigidity :€“ Changing one part of code might affect other parts of the code
  2. Fragility :€“ One change might lead to unexpected changes from other parts
  3. Immobility :€“ Reuse of the code is impossible because the application is so much tangled already.

 

Spring uses Dependency Injection[DI] as a rescue for this problem. The underlying classes are made abstract and the instantiation, management and class casting of the objects are done by the spring framework’€™s IOC container.

IOC_Framework

It is clear from the above pictorical representation, Spring container acts as a bridge between the abstract POJO classes which contains the blue print of the required model and the metadata which provides data for the POJO classes. This way, there is no dependency for classes on one another. Making the programming abstract through dependency injection is the solution for handling the above stated problems which are mainly associated with development, enhancement and maintenance of large codes.

 

 

Read More

Spring Tutorial for Java Beginners

Posted by on Apr 20, 2013 in Spring, Spring Tutorial | 0 comments

 
spring logo
 
The Spring Framework is a lightweight framework for developing Java enterprise applications. It provides high performing, easily testable and reusable code. Spring handles the infrastructure as the underlying framework so that you can focus on your application.Spring is modular in design, thereby making creation, handling and linking of individual components so much easier. Spring implements Model View Container(MVC) design pattern.
 
In this tutorial, we’ll take you step by step towards mastering the spring concepts.
Here you go!!!! :)

 

Spring Basics

1. Spring framework architecture

Gives you an insight of the architectural framework of Spring.

2. Basic concepts of Spring

This link provides any beginner, a start up at the basic concepts of Spring.

3. Inversion Of Control(IOC)

The IOC container is at the core of Spring framework. Read on to understand why this was needed and how it functions.

 

Basic tutorials with spring

1. Spring set up
Eclipse IDE set up and start up configurations for Spring support.

2. First hands-on with spring

Your first attempt at creating and running spring program at its simplest.

3. JavaConfig to provide Spring metadata

The configuration metadata can also be provided using a JavaConfig file. Click on to see more.

 

Dependency Injection(DI)

1. Dependency Injection(DI) in spring

What exactly is Dependency Injection and why is it needed? What are the types of DI supported by Spring.

2. Basic example of Setter injection in spring
Basic example of setting values to attributes (of primitive Data Types to a class through the bean using setter injection

3. Basic example of Constructor injection in spring
Basic example of setting values to attributes (of primitive Data Types to a class through the bean using constructor injection

4. Setter injection for reference bean

How setter injection is done when an attribute of a class is another class.

5. Constructor injection for reference bean

How constructor injection is done when an attribute of a class is another class.

6. Constructor injection – ambiguities

Ambiguities that might arise while passing values to constructor parameters through injection.

 

Bean

1. Basics of Bean

What is a Bean and also what are the various scopes available in Bean.

2. Loading multiple configuration metadata files

How to load multiple configuration metadata files in spring.

3. Bean Scopes

Understanding the scope and life cycle of bean.

4. Bean of Singleton scope
Example of spring bean of singleton scope

5. Bean of Prototype scope
Example of spring bean of prototype scope

6. Working with Set,List,Map and Properties as attributes

Having List, set, map and properties as attributes of a bean class.

7. List FactoryBean, Set FactoryBean and Map FactoryBean

Dealing with ArrayList,LinkedList, TreeSet,HashSet,TreeMap,HashMap

8. Using life cycle events on a bean

The life cycle events of a bean can be used to set values to the attributes of a bean using the init method.

 

Spring Expression Language(spEL)

1. Basics of spEL

Gives the basics of what is spEL and what are its features.

2. Basic example using spEL

First hands on using spEL to create and run a simple program using spEL

3. simple spEL using Annotation

Basic hands on using spEL wherein, java annotations are used instead of xml for providing the configuration metadata.

4. Dot operator on Bean reference

Dot operator can be used to reference the attribues of the bean.

5. Bean Method invocation using spEL

Dot operator can further be used to place calls to methods inside the referenced bean.

6. Operators in spEL

Usage of mathematical, relational, logical and ternary operators in spEL

7. Accessing Map and List attributes in spEL

Using spEL to access Map and List attributes inside a bean.

 

Aspect Oriented Programming(AOP)

1. Basics of Aspect Oriented Programming(AOP)

What is AOP. Why is it such an integral part of Spring. Terminologies, concepts and set up.

2. Basic example of Spring AOP Concept using BeforeAdvice

Taking up BeforeAdvice to understand the basic working of AOP concept.

3. Spring AOP BeforeAdvice, AfterReturningAdvice

Adding on AfterReturningAdvice functionality to the previously tried out BeforeAdvice, with a slight change in the scenario.

4. Spring AOP – AfterThrows Advice

Implementing AfterThrows Advice to implement a functionality once a method throws an exception.

5. Spring AOP – Around Advice

A one stop shop for the above 3 mentioned functionalities. A combination of Before, AfterReturning and AfterThrows functionality in Around Advice

 

Read More

Using life cycle events on a bean

Posted by on Feb 7, 2013 in Spring, Spring Tutorial | 0 comments

 


 
The life cycle events of a bean can be used to set values to the attributes of a bean using the init method.
We can associate the life cycle events of a bean to make calls to corresponding init and destroy method. The init and destroy method associated with a bean are given along with the bean definition. This way, a call is automatically made to these methods, as per the bean’s state.

Init method is called once the property of the bean is set.
Destroy method is called when the context associated with the bean is closed. This is when all the resources related to the context are cleared.

Step 1 :

Create a POJO with a method each for defining the steps to be taken at initial and destroy step. Note that the method name is user defined

File : Amount.java
 

package com.simpleCodeStuffs;

public class Amount {
	private String val;

	public String getVal() {
		return val;
	}

	public void setVal(String val) {
		this.val = val;
	}

	public String toString(){
		return ("amount bean val: "+val);
	}
	
	public void startUp(){
	     System.out.println("init() method called after properties to Amount are set. ");
	     System.out.println(toString());
	}
	
	public void cleanUp(){
	     System.out.println("destroy method called when application context is closed");
	     System.out.println("Releasing/destroying all resources");
	     System.out.println(toString());
	}
	}

 

Step 2 :

Bean definition is given along with the init and destroy values. The method names correspondingly are given here.

‘init-method’ and ‘destroy-method’ attributes are used along with the bean definition ‘bean’ tag, to specify the methods to be called during the start up and destruction stage of the bean

 
File : 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="amount" class="com.simpleCodeStuffs.Amount" init-method="startUp"
		destroy-method="cleanUp">
		<property name="val" value="SimpleCodeStuff--HelloWorld" />
	</bean>
</beans>

 

Step 3 : Create the main class

 
File : MainClass.java
 

package com.simpleCodeStuffs;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {
	public static void main(String[] args) {
		
	ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "Beans.xml" });
		Amount amt = (Amount) context.getBean("amount");
		System.out.println("printing amount in main class " + amt);
		
	}
}

 

Step 4: Run it. The output appears as below

 

lifecycleOutput

Notice that, the destroy method has never been called. This is because the context is not closed.

 

Step 5 :

Make modifications in the main class to close the context. Note,we have initially used it as
 

  ApplicationContext context = 
	   new ClassPathXmlApplicationContext(new String[] {"Beans.xml"});
Amount amt=(Amount)context.getBean("amount");

 

But, close() method is not defined on ApplicationContext. The method is rather defined on the implementation ClassPathXmlApplicationContext. So let us modify that part as well  to implement our changes. Now the main class is
 

package com.simpleCodeStuffs;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {
	public static void main(String[] args) {
	    ClassPathXmlApplicationContext context =
	   	 new ClassPathXmlApplicationContext(new String[] {"Beans.xml"}); 
                context.close()
//		ApplicationContext context = new ClassPathXmlApplicationContext(
//				new String[] { "Beans.xml" });
		Amount amt = (Amount) context.getBean("amount");
		System.out.println("printing amount in main class " + amt);
		context.close(); // destroy method is called here
	}
}

 

Step 6 : Run it. Now the output appears as :-

 

lifeCycleModifiedOutput

 


 

Read More

Accessing Map and List attributes in spEL

Posted by on Feb 6, 2013 in Spring, Spring Tutorial | 0 comments

 

Step 1 :Create the POJO

 

The bean is defined using @Component annotation. The values of the Map and List are set in the constructor.

File : Bean.java
 

package com.simpleCodeStuffs.spEL;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component("testBean")
public class Bean {

	private Map<String, String> name;

	private List<Integer> price;

	public Bean() {

		name = new HashMap<String, String>();
		name.put("a", "Sandy");
		name.put("b", "Poorni");
		name.put("c", "Gokul");
		price = new ArrayList<Integer>();
		price.add(150);
		price.add(200);
		price.add(570);
	}

	public Map<String, String> getName() {
		return name;
	}

	public void setName(Map<String, String> name) {
		this.name = name;
	}

	public List<Integer> getPrice() {
		return price;
	}

	public void setPrice(List<Integer> price) {
		this.price = price;
	}
}

 

Notice how values are injected using spEL in the below class

File : Customer.java
 

package com.simpleCodeStuffs.spEL;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("custBean")
public class Customer {

	@Value("#{testBean.name['c']}")
	private String name;

	@Value("#{testBean.price[0]}")
	private double bill;

	public String getName() {
		return name;
	}

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

	public double getBill() {
		return bill;
	}

	public void setBill(double bill) {
		this.bill = bill;
	}
}

 

In case of MAP {#beanID.<propertyName>[‘MapIndex’]} In case of List {#beanID.<propertyName>[indexValue]}

 

Step 2 : Create the main class

 
File : MainClass.java
 

package com.simpleCodeStuffs.spEL;

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

public class MainClass {

	public static void main(String[] args) {

		ApplicationContext context = 
			  new ClassPathXmlApplicationContext("elBeans.xml");
		Customer customer = (Customer) context.getBean("cust");
		
		System.out.println("Customer name: " + customer.getName());
		System.out.println("Bill price : " + customer.getBill());
	}
}

 

Step 3 :

Note that the values are accessed using annotations in this example. So, do not provide values in the xml as well, as the values provided in xml usually override the values provided through annotations.

 

File : elBeans.xml

<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:component-scan base-package="com.simpleCodeStuffs.spEL" />
	<bean id="cust" class="com.simpleCodeStuffs.spEL.Customer">
	</bean>
</beans>

 

Step 4 : Run the program. The output is

 

spelListMapOutut

 

 

Read More

Bean of Prototype scope

Posted by on Jan 28, 2013 in Spring, Spring Tutorial | 0 comments

 
 


 
This scope of bean can be utilised when more than one instance of a particular bean is required during the span of an application. It teturn a new bean instance each time a request is made.

Step 1 : Define the POJO

 
File : Amount.java
 

package com.simpleCodeStuffs;

public class Amount {

private String val;
public String getVal() {
return val;
}

public void setVal(String val) {
this.val = val;
}
}

 

In prototype scope,a new instance of the bean is returned per request. (every time getBean() method is called)

 

Step 2 : Define the bean definition

 
File : 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="amount" class="com.simpleCodeStuffs.Amount" scope="prototype">
	</bean>
</beans>

 
Note, only the bean is defined. Property values are injected from the main class in order to provide some clarity on the subject. Also note, the scope has been mentioned as ‘prototype’ in the bean definition. Therefore, an instance of the bean will be returned every time a request is made.

 

Step 3 : Create the main class

 
File : MainClass.java
 

package com.simpleCodeStuffs;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.simpleCodeStuffs.Amount;

public class MainClass {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Amount Firstamt=(Amount)context.getBean("amount");
/* instance of bean returned*/
Firstamt.setVal("SimpleCodeStuffs");

System.out.println(Firstamt.getVal());

Amount Secondamt=(Amount)context.getBean("amount");
/*For PROTOTYPE scope, new bean instance is returned */

System.out.println(Secondamt.getVal());
}
}

 

Note that the bean is of scope “prototype”€™. So an instance of the bean is returned everytime a request is made using getBean() method. So, a new instance is returned for Secondamt and no value has been set for the new instance. This can be seen in output as Secondamt prints null value.
 

Step 4 : Run the application. The output is

 

prototype

 


 

Read More