Pages Navigation Menu

Coding is much easier than you think

Spring – Java config file providing the configuration metadata

Posted by in Spring

 
spring logo
 
download
 
In the previous example, we observed the working of spring at its simplest . The main part of injecting the dependency value here, was taken up by the Configuration metadata xml file (Beans.xml). Another option supported by spring is to set this information through a java configuration file.
 
** UPDATE: Spring Complete tutorial now available here.
 

1 Create the POJO €“ HelloWorld.java

 

File : HelloWorld.java
 

package com.simpleCodeStuffs;

public class HelloWorld {

public HelloWorld(){

System.out.println("In constructor of HelloWorld");

}

private String message;

public void setMessage(String message){

this.message  = message;

}

public void getMessage(){

System.out.println("Your Message : " + message);

}

}

 

Step 2 :

 
Previously, the metadata was provided through xml (Beans.xml)using various xml tags. Now let us define the java configuration equivalent of the same which makes use of annotations to provide the configuration data. Create a new class JavaConfig under the same package.

The configuration metadata is provided through a java configuration class, using annotations

File :JavaConfig.java

 

package com.simpleCodeStuffs;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class JavaConfig {

@Bean(name="helloWorld")

public HelloWorld helloWorld(){

HelloWorld bean = new HelloWorld();

System.out.println("helloWorld bean through Java Config");

bean.setMessage("JavaConfig msg- SimpleCodeStuffs");

return bean;

}

}

 

AnnotationDescription
@ConfigurationStates that this class is used by Spring to provide bean definition. An application may have one or more classes with @Configuration
@Beanattributes :- 

a) Name

b) initMethodName

c) destroyMethodName

d) Scope

It is a method level annotation. The return value of the methods annotated with @Bean is registered as a bean by BeanFactory.a) This is used to explicitly mention the name of the bean. By default the bean name is same as the method name.b) The method to be called for the bean initialization

c) The method to be called at the end of the bean lifecycle.

d) Defines the scope of bean. By default it is taken as ‘singleton’.

 

@importThe functionality is similar to <import resource=”..”/> in xml file.

 

In case of dependencies between beans, then in place of using ref=€<beanID>€ in the xml config, here a method call is placed between the beans.

 
This can be done as follows
 
File : JavaConfig.java
 
@Configuration

public class JavaConfig {

@Bean

public Candidate candidate() {

return new Candidate(address());

}

@Bean

public Address address() {

return new Address ();

}

}

 
In this case, Address is an attribute inside Candidate. Hence the value for the Address bean is injected by passing a call to address() bean method from Candidate’€™s bean method.
 

3. Create a main class for running the above example

 

File : MainJavaConfig.java

package com.simpleCodeStuffs;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainJavaConfig {

public static void main(String args[]){

ApplicationContext context =
           new AnnotationConfigApplicationContext(JavaConfig.class);

HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

obj.getMessage();

}

}

 

4 : Demo

Run the Main class. The output is as follows

 

JavaConfigOutput

 
download
 

Read More

Spring Environment Setup

Posted by in Spring, Spring Tutorial

 
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 !! Read More

Spring Inversion Of Control

Posted by in Spring, Spring Tutorial

 
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 in Spring, Spring Tutorial

 
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

List FactoryBean, Set FactoryBean and Map FactoryBean in Spring

Posted by in Spring

 

 

We have previously seen how to deal with List, Set and Map type attributes inside a bean class. Further let us venture into having concrete List collection (ArrayList and LinkedList), Set collection(HashSet and TreeSet)  Map collection(HashMap and TreeMap)

 

Step 1 : Create the POJO

 
File : ClassABC.java
 


package com.simpleCodeStuffs;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class ClassABC {

	private List listVariable;
	private Map mapVariable;
	private Set setVariable;

	public List getListVariable() {
		return listVariable;
	}

	public void setListVariable(List listVariable) {
		this.listVariable = listVariable;
	}

	public Map getMapVariable() {
		return mapVariable;
	}

	public void setMapVariable(Map mapVariable) {
		this.mapVariable = mapVariable;
	}

	public Set getSetVariable() {
		return setVariable;
	}

	public void setSetVariable(Set setVariable) {
		this.setVariable = setVariable;
	}

	public String toString() {
		return ("listVariable t" + listVariable + "nsetVariable t"
				+ setVariable + "nmapVariable t" + mapVariable);
	}
}

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);
	}
}

 

Step 2 : Provide the configuration metadata in the xml file

 

To support the concrete classes of List, Map and Set, it is essential to include util schema in the Beans.xml file.Else, you will end up getting a

SAXParseException because of it

 

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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<bean id="abc" class="com.simpleCodeStuffs.ClassABC">
	<property name="listVariable">
		<util:list list-class="java.util.ArrayList">
			<value>1</value>
			<value>ArrayList</value>
			<ref bean="amount" />
		</util:list>
	</property>

	<property name="setVariable">
		<util:set set-class="java.util.HashSet">
			<value>2</value>
			<value>HashSet</value>
			<ref bean="amount" />
		</util:set>
	</property>

	<property name="mapVariable">
		<util:map map-class="java.util.HashMap">
			<entry key="Key1" value="3" />
			<entry key="Key2" value="HashMap" />
			<entry key="Key3" value-ref="amount" />
		</util:map>
	</property>
</bean>

<bean id="amount" class="com.simpleCodeStuffs.Amount">
	<property name="val" value="simpleCodeStuffs" />
</bean>
</beans>

 

Step 3 :

 
File : MainClass.java
 

package com.simpleCodeStuffs;

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

public class MainClass
{
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
	ClassABC abc = (ClassABC) context.getBean("abc");
	System.out.println(abc);
}
}

 

Step 4: Run the application. The output is

 

listMapFactoryOutput

 


  Read More

Using life cycle events on a bean

Posted by in Spring, Spring Tutorial

 


 
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
Page 1 of 41234