Spring Batch – Overview ”; Previous Next Batch processing is a processing mode which involves execution of series of automated complex jobs without user interaction. A batch process handles bulk data and runs for a long time. Several Enterprise applications require to process huge data to perform operations involving − Time-based events such as periodic calculations. Periodic applications that are processed repetitively over large datasets. Applications that deals with processing and validation of the data available in a transactional manner. Therefore, batch processing is used in enterprise applications to perform such transactions. What is Spring Batch Spring batch is a lightweight framework which is used to develop Batch Applications that are used in Enterprise Applications. In addition to bulk processing, this framework provides functions for − Including logging and tracing Transaction management Job processing statistics Job restart Skip and Resource management You can also scale spring batch applications using its portioning techniques. Features of Spring Batch Following are the notable features of Spring Batch − Flexibility − Spring Batch applications are flexible. You simply need to change an XML file to alter the order of processing in an application. Maintainability − Spring Batch applications are easy to maintain. A Spring Batch job includes steps and each step can be decoupled, tested, and updated, without effecting the other steps. Scalability − Using the portioning techniques, you can scale the Spring Batch applications. These techniques allow you to − Execute the steps of a job in parallel. Execute a single thread in parallel. Reliability − In case of any failure, you can restart the job from exactly where it was stopped, by decoupling the steps. Support for multiple file formats − Spring Batch provides support for a large set of readers and writers such as XML, Flat file, CSV, MYSQL, Hibernate, JDBC, Mongo, Neo4j, etc. Multiple ways to launch a job − You can launch a Spring Batch job using web applications, Java programs, Command Line, etc. In addition to these, Spring Batch applications support − Automatic retry after failure. Tracking status and statistics during the batch execution and after completing the batch processing. To run concurrent jobs. Services such as logging, resource management, skip, and restarting the processing. Print Page Previous Next Advertisements ”;
Category: Java
Spring Batch – Home
Spring Batch Tutorial PDF Version Quick Guide Resources Job Search Discussion Spring Batch is a lightweight framework which is used to develop Batch Applications that are used in Enterprise Applications. This tutorial explains the fundamental concepts of Spring Batch and shows how you can use it in practical environment. Audience This tutorial is particularly going to be useful for all those professionals who are required to process large volumes of records involving repetitive actions such as transaction management, job processing statistics, resource management, etc. Spring Batch is a very effective framework for processing high-volume batch jobs. Prerequisites Spring Batch has been built upon Spring Framework, therefore you should have prior exposure to the features and functions of Spring. In case you are not familiar with Spring Framework, then you can start here. Print Page Previous Next Advertisements ”;
Annotation Based After Returning Advice ”; Previous Next @AfterReturning is an advice type, which ensures that an advice runs after the method executes successfully. Following is the syntax of @AfterReturning advice. Syntax @AfterReturning(Pointcut = “execution(* com.tutorialspoint.Student.*(..))”, returning = “retVal”) public void afterReturningAdvice(JoinPoint jp, Object retVal){ System.out.println(“Method Signature: ” + jp.getSignature()); System.out.println(“Returning:” + retVal.toString() ); } Where, @AfterReturning − Mark a function as an advice to be executed before method(s) covered by Pointcut, if the method returns successfully. Pointcut − Provides an expression to select a function execution( expression ) − Expression covering methods on which advice is to be applied. returning − Name of the variable to be returned. To understand the above-mentioned concepts related to @AfterReturning Advice, let us write an example, which will implement @AfterReturning Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; @Aspect public class Logging { /** * This is the method which I would like to execute * after a selected method execution. */ @AfterReturning(Pointcut = “execution(* com.tutorialspoint.Student.*(..))”, returning = “retVal”) public void afterReturningAdvice(JoinPoint jp, Object retVal){ System.out.println(“Method Signature: ” + jp.getSignature()); System.out.println(“Returning:” + retVal.toString() ); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; 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”); Student student = (Student) context.getBean(“student”); student.getAge(); } } Following is the configuration 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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Age : 11 Method Signature: Integer com.tutorialspoint.Student.getAge() Returning 11 Print Page Previous Next Advertisements ”;
Spring AOP – Before Aspect
Spring AOP – Annotation Based Before Advice ”; Previous Next @Before is an advice type which ensures that an advice runs before the method execution. Following is the syntax of @Before advice. Syntax @Pointcut(“execution(* com.tutorialspoint.Student.getName(..))”) private void selectGetName(){} @Before(“selectGetName()”) public void beforeAdvice(){ System.out.println(“Going to setup student profile.”); } Where, @Pointcut − Mark a function as a Pointcut execution( expression ) − Expression covering methods on which advice is to be applied. @Before − Mark a function as an advice to be executed before method(s) covered by Pointcut. To understand the above-mentioned concepts related to @Before Advice, let us write an example which will implement @Before Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application − Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Before; @Aspect public class Logging { /** Following is the definition for a Pointcut to select * all the methods available. So advice will be called * for all the methods. */ @Pointcut(“execution(* com.tutorialspoint.Student.getName(..))”) private void selectGetName(){} /** * This is the method which I would like to execute * before a selected method execution. */ @Before(“selectGetName()”) public void beforeAdvice(){ System.out.println(“Going to setup student profile.”); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; 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”); Student student = (Student) context.getBean(“student”); student.getName(); student.getAge(); } } Following is the configuration 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:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Going to setup student profile. Name : Zara Age : 11 The above-defined @Pointcut uses an expression to select method getAge() defined in class(es) under the package com.tutorialspoint. @After advice uses the above-defined Pointcut as a parameter. Effectively afterAdvice() method will be called before every method covered by the above Pointcut. Print Page Previous Next Advertisements ”;
Spring AOP – Discussion
Discuss Spring AOP ”; Previous Next One of the key components of Spring Framework is the Aspect Oriented Programming (AOP) framework. Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. This tutorial will take you through simple and practical approaches while learning AOP framework provided by Spring. Print Page Previous Next Advertisements ”;
Spring SpEL – Collection Projection ”; Previous Next SpEL expression supports Collection Projection which is a very powerful expression allowing to evaluate sub-expression and in result returns a new collection. Syntax ![projectionExpresion] Following example shows the usage. List<String> list = (List<String>) parser.parseExpression(“employees.![country]”).getValue(deptContext); Here SpEL will return only those employees from the list of employees whose country is USA. Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − Employee.java − Employee class. Dept.java − Department class. MainApp.java − Main application to run and test. Here is the content of Employee.java file − package com.tutorialspoint; public class Employee { private String name; private String country; public Employee(String name, String country) { this.name = name; this.country = country; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String toString() { return “[” +name+ “, “+country + “]”; } } Here is the content of Dept.java file − package com.tutorialspoint; import java.util.List; public class Dept { private List<Employee> employees; public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); Employee employee1 = new Employee(“Robert”, “USA”); Employee employee2 = new Employee(“Julie”, “USA”); Employee employee3 = new Employee(“Ramesh”, “India”); List<Employee> employees = new ArrayList<Employee>(); employees.add(employee1); employees.add(employee2); employees.add(employee3); Dept dept = new Dept(); dept.setEmployees(employees); EvaluationContext deptContext = new StandardEvaluationContext(dept); // Select list of countries List<String> list = (List<String>) parser.parseExpression(“employees.![country]”).getValue(deptContext); System.out.println(list); } } Output [USA, USA, India] Print Page Previous Next Advertisements ”;
Spring DI – Map Setter
Spring DI – Map Setter ”; Previous Next You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean. Now what if you want to pass Map. In this example, we”re showcasing passing direct values of the Map using setter injection. Example The following example shows a class JavaCollection that is using collections as dependency injected using setter method. Let”s update the project created in Spring DI – Create Project chapter. We”re adding following files − JavaCollection.java − A class containing a collections as dependency. MainApp.java − Main application to run and test. Here is the content of JavaCollection.java file − package com.tutorialspoint; import java.util.*; public class JavaCollection { Map<String, String> addressMap; public JavaCollection() {} public JavaCollection(Map<String, String> addressMap) { this.addressMap = addressMap; } // a setter method to set Map public void setAddressMap(Map<String, String> addressMap) { this.addressMap = addressMap; } // prints and returns all the elements of the Map. public Map<String, String> getAddressMap() { System.out.println(“Map Elements :” + addressMap); return addressMap; } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“applicationcontext.xml”); JavaCollection jc=(JavaCollection)context.getBean(“javaCollection”); jc.getAddressMap(); } } Following is the configuration file applicationcontext.xml which has configuration for all the type of collections − <?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 = “javaCollection” class = “com.tutorialspoint.JavaCollection”> <property name = “addressMap”> <map> <entry key = “1” value = “INDIA”/> <entry key = “2” value = “JAPAN”/> <entry key = “3” value = “USA”/> <entry key = “4” value = “UK”/> </map> </property> </bean> </beans> Output Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Map Elements :{1=INDIA, 2=JAPAN, 3=USA, 4=UK} Print Page Previous Next Advertisements ”;
Spring SpEL – XML Based Configuration ”; Previous Next SpEL expression can be used in XML based beans configuration Syntax Following is an example of using an expression in xml configuration. <bean id=”randomNumberGenerator” class=”com.tutorialspoint.RandomNumberGenerator”> <property name=”randomNumber” value=”#{ T(java.lang.Math).random() * 100.0 }”/> </bean> Here we have specified a property to be filled in using Math.random() method. In case of classes, its name should be fully qualified. We can use system variables as well using systemProperties. It is a built-in variable. <property name=”country” value=”#{ systemProperties[”user.country”] }”/> We can use another bean as well with a SpEL expression as shown below: <property name=”id” value=”#{ randomNumberGenerator.randomNumber }”/> Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − RandomNumberGenerator.java − A random number generator class. Employee.java − An employee class. MainApp.java − Main application to run and test. applicationcontext.xml − beans configuration file. Here is the content of RandomNumberGenerator.java file − package com.tutorialspoint; public class RandomNumberGenerator { private int randomNumber; public int getRandomNumber() { return randomNumber; } public void setRandomNumber(int randomNumber) { this.randomNumber = randomNumber; } } Here is the content of Employee.java file − package com.tutorialspoint; public class Employee { private int id; private String name; private String country; 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 String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return “[” + id + “, ” + name + “, ” + country + “]”; } } Here is the content of MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“applicationcontext.xml”); Employee employee = (Employee) applicationContext.getBean(“employee”); System.out.println(employee); } } Here is the content of applicationcontext.xml file − <?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=”randomNumberGenerator” class=”com.tutorialspoint.RandomNumberGenerator”> <property name=”randomNumber” value=”#{ T(java.lang.Math).random() * 100.0 }”/> </bean> <bean id=”employee” class=”com.tutorialspoint.Employee”> <property name=”id” value=”#{ randomNumberGenerator.randomNumber }”/> <property name=”country” value=”#{ systemProperties[”user.country”] }”/> <property name=”name” value=”Mahesh”/> </bean> </beans> Output [84, Mahesh, IN] Print Page Previous Next Advertisements ”;
Spring DI – Autowiring ByType ”; Previous Next This mode specifies autowiring by property type. Spring container looks at the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired. For example, if a bean definition is set to autowire byType in the configuration file, and it contains a spellChecker property of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example will illustrate the concept. Example The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection. Let”s update the project created in Spring DI – Create Project chapter. We”re adding following files − TextEditor.java − A class containing a SpellChecker as dependency. SpellChecker.java − A dependency class. MainApp.java − Main application to run and test. Here is the content of TextEditor.java file − package com.tutorialspoint; public class TextEditor { private SpellChecker spellChecker; private String name; public void setSpellChecker( SpellChecker spellChecker ){ this.spellChecker = spellChecker; } public SpellChecker getSpellChecker() { return spellChecker; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void spellCheck() { spellChecker.checkSpelling(); } } Following is the content of another dependent class file SpellChecker.java − package com.tutorialspoint; public class SpellChecker { public SpellChecker(){ System.out.println(“Inside SpellChecker constructor.” ); } public void checkSpelling(){ System.out.println(“Inside checkSpelling.” ); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“applicationcontext.xml”); TextEditor te = (TextEditor) context.getBean(“textEditor”); te.spellCheck(); } } Following is the configuration file applicationcontext.xml which has configuration for autowiring byName − <?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”> <!– Definition for textEditor bean –> <bean id = “textEditor” class = “com.tutorialspoint.TextEditor” autowire = “byType”> <property name = “name” value = “Generic Text Editor” /> </bean> <!– Definition for spellChecker bean –> <bean id = “spellChecker” class = “com.tutorialspoint.SpellChecker”></bean> </beans> Output Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Inside SpellChecker constructor. Inside checkSpelling. Print Page Previous Next Advertisements ”;
Spring SpEL – List
Spring SpEL – List ”; Previous Next SpEL expression supports accessing list and using their indexes of an list of an object. We can access nested lists as well within an SpEL expression. Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − Employee.java − Employee class. Dept.java − Department class. MainApp.java − Main application to run and test. Here is the content of Employee.java file − package com.tutorialspoint; public class Employee { private List<String> awards; public List<String> getAwards() { return awards; } public void setAwards(List<String> awards) { this.awards = awards; } } Here is the content of Dept.java file − package com.tutorialspoint; public class Dept { private List<Employee> employees; public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.Arrays; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); Employee employee = new Employee(); employee.setAwards(Arrays.asList(“Star of the Month”, “Champion”, “Accelerator”)); Dept dept = new Dept(); dept.setEmployees(Arrays.asList(employee)); EvaluationContext employeeContext = new StandardEvaluationContext(employee); // evaluates to “Accelerator” String award = parser.parseExpression(“awards.get(2)”).getValue(employeeContext, String.class); System.out.println(award); EvaluationContext deptContext = new StandardEvaluationContext(dept); // evaluates to “Champion” award = parser.parseExpression(“employees.get(0).awards.get(1)”).getValue(deptContext, String.class); System.out.println(award); } } Output Accelerator Champion Print Page Previous Next Advertisements ”;