<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog4Java &#187; Springsource</title>
	<atom:link href="http://malsolo.com/blog4java/?cat=8&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://malsolo.com/blog4java</link>
	<description>A personal and Java blog, likely only for me</description>
	<lastBuildDate>Tue, 31 Mar 2015 15:52:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.1</generator>
	<item>
		<title>Orika time!</title>
		<link>http://malsolo.com/blog4java/?p=465</link>
		<comments>http://malsolo.com/blog4java/?p=465#comments</comments>
		<pubDate>Thu, 23 Oct 2014 15:52:56 +0000</pubDate>
		<dc:creator><![CDATA[Javier (@jbbarquero)]]></dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Springsource]]></category>
		<category><![CDATA[Mapping]]></category>
		<category><![CDATA[Orika]]></category>
		<category><![CDATA[POJO]]></category>

		<guid isPermaLink="false">http://malsolo.com/blog4java/?p=465</guid>
		<description><![CDATA[I love good software, and Orika is a really interesting project. In this post I&#8217;m going to talk about this Java bean mapping framework that I&#8217;ve used recently and I highly recommend. Orika (formerly hosted at google code) claims to &#8230; <a href="http://malsolo.com/blog4java/?p=465">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I love good software, and Orika is a really interesting project. In this post I&#8217;m going to talk about this Java bean mapping framework that I&#8217;ve used recently and I highly recommend.</p>
<p><a href="http://orika-mapper.github.io/orika-docs/" title="Orika User Guide" target="_blank">Orika</a> (formerly hosted at <a href="https://code.google.com/p/orika/" title="Orika at google code" target="_blank">google code</a>) claims to be a <em>simpler, lighter and faster Java bean mapping</em>. And it really is.</p>
<p>It allows you to convert objects by copying its attributes from one to another. It performs this by using Java introspection, instead of XML configuration or something like that. It uses code generation to create the mappers, and it has an interesting strategy for its core classes that allows you to optimize the performance.</p>
<p>It is completely configurable, for instance, the java code generator by default is Javassist, but you can use EclipseJdt or even use another provider by implementing the appropriate interface.</p>
<p>Finally, it&#8217;s a very well documented project, with clear explanations and useful code.</p>
<p>I really like it.</p>
<p>If you want to try it, just add the next dependency to your maven project:</p>
<p></p><pre class="crayon-plain-tag">&lt;dependency&gt;
			&lt;groupId&gt;ma.glasnost.orika&lt;/groupId&gt;
			&lt;artifactId&gt;orika-core&lt;/artifactId&gt;
			&lt;version&gt;1.4.5&lt;/version&gt;&lt;!-- or latest version --&gt;
		&lt;/dependency&gt;</pre><p></p>
<p>Or <a href="https://github.com/orika-mapper/orika/releases" title="Orika releases at GitHub" target="_blank">download the library</a> along with three required libraries:</p>
<ul>
<li>javassist (v 3.12.0+)</li>
<li>slf4j (v 1.5.6+)</li>
<li>paranamer (v 2.0+)</li>
</ul>
<h1>Main concepts</h1>
<p>There are two core classes, the first one is <strong>MapperFactory</strong>, the class to configure the mappings and to obtain the second core class: <strong>MapperFacade</strong>, that actually provides the service of a Java bean mapping.</p>
<h3>MapperFactory</h3>
<p>By using a fluent API, you can construct a <strong>MapperFactory</strong> via its main implementation, <strong>DefaultMapperFactory</strong> and its static class helpers intended for building the <strong>MapperFactory</strong>.</p>
<p>Then you can obtain a <strong>ClassMapBuilder</strong> from the <strong>MapperFactory</strong> in order to declare the mapping configuration in a fluent-style, that is: mapping fields (bi-directional by default, or in one direction if you&#8217;d rather), excluding fields, specifying constructors and customizing mappings of Lists, Sets, nested fields and so on.</p>
<p>There is a default mapping that maps fields with matching names between two classes, and you can also register the mapping in the MapperFactory (the ClassMapBuilder is built with the very MapperFactory as atribute). Both operations have the appropriate methods to be called.</p>
<p>Let&#8217;s see an example:</p>
<p>We have two classes: <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/dto/PersonDTO.java" title="PersonDTO at github" target="_blank">PersonDTO</a> and <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/domain/Person.java" title="Person at github" target="_blank">Person</a>, and we want to convert one object for the former class to an object of the latter one, so let&#8217;s configure the MapperFactory:</p>
<p></p><pre class="crayon-plain-tag">MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
mapperFactory.classMap(PersonDTO.class, Person.class) //A ClassMapBuilder&lt;PersonDTO, Person&gt;
        .field(&quot;lastNames&quot;, &quot;surnames&quot;) //Register field mappings
        .field(&quot;streetAddress&quot;, &quot;address.street&quot;)
        .field(&quot;city&quot;, &quot;address.city&quot;)
        .field(&quot;postalCode&quot;, &quot;address.zipCode&quot;)
        .byDefault() //the remaining fields on both classes should be mapped matching the fields by name
        .register(); //register the mapping with the MapperFactory.</pre><p></p>
<p>The <strong>ClassMapBuilder</strong> provides interesting mappings for excluding fields, mapping fields in one direction only (as I mentioned above, mapping is by default bi-directional) and so on. See the <a href="http://orika-mapper.github.io/orika-docs/mappings-via-classmapbuilder.html" title="Declarative Mapping Configuration: using the fluent-style ClassMapBuilder API " target="_blank">Declarative Mapping Configuration</a> and <a href="http://orika-mapper.github.io/orika-docs/advanced-mappings.html" title="Advanced Mapping Configurations: beyond the basics of ClassMapBuilder API" target="_blank">Advanced Mapping Configurations</a> for more options.</p>
<h3>MapperFacade and BoundMapperFacade</h3>
<p>The <strong>MapperFacade</strong> performs the actual mapping work, for doing so, you have to obtain the MapperFacade from the MapperFactory and then use its map methods. There are two general options, <strong><em>map(objectA, B.class)</em></strong>, which will create a new instance of B.class and map the property values of objectA onto it, or <strong><em>map(objectA, objectB)</em></strong>, which copies properties from objectA onto objectB, being both of them not null.</p>
<p>Let&#8217;s see an example: </p>
<p></p><pre class="crayon-plain-tag">MapperFacade mapper = mapperFactory.getMapperFacade();
PersonDTO personDTO = new PersonDTO();
//Set values here
Person person = mapper.map(personDTO, Person.class);
//Alternatively:
//Person person = new Person();
//mapper.map(personDTO, person);</pre><p></p>
<p>The <strong>BoundMapperFacade</strong> is intended to be used with a pair of types to map and no further customization needed. It provides improved performance over use of the standard <strong>MapperFacade</strong> and it has the same usage plus a <strong><em>mapReverse</em></strong> method for mapping in the reverse direction.</p>
<p>See below an example:</p>
<p></p><pre class="crayon-plain-tag">BoundMapperFacade&lt;PersonDTO, Person&gt; boundMapper = mapperFactory.getMapperFacade(PersonDTO.class, Person.class);
PersonDTO personDTO = new PersonDTO();
//Set values here
Person person = boundMapper.map(personDTO);
//Alternatively:
//Person person = new Person();
//boundMapper.map(personDTO, person);
//Map in the reverse
PersonDTO personDTO = boundMapper.mapReverse(person);
//Alternatively with no null objects:
//boundMapper.mapReverse(person, personDTO); //curiously, it returns an A object instead of void</pre><p></p>
<p>If you’re primarily concerned with the mapping of a particular type to another, and your object graph has no cycles, use <strong>BoundMapperFacade</strong> because it has <u>better performance</u>, since you avoid the overhead of looking up an appropriate mapping strategy for the fields of the objects to be mapped, that happens when you call the map method.</p>
<h3>Performance</h3>
<p>The most expensive operations are instantiation and initialization of the MapperFactory, and the MapperFacade which is obtained from it.</p>
<p>Both of them are thread-safe objects, thus singletons or static access for them are a very recommended approach.</p>
<p>For instance, you can consider an static acces to the MapperFactory:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.domain.mappers;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

public class BaseMapper {
    final static MapperFactory MAPPER_FACTORY = new DefaultMapperFactory.Builder().build();
}</pre><p></p>
<p>And then use this class for registering class maps and access to the MapperFacade in a customize way:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.domain.mappers;

import com.malsolo.orika.test.domain.Customer;
import com.malsolo.orika.test.dto.CustomerDTO;
import ma.glasnost.orika.MapperFacade;

public enum CustomerMapper {
    
    INSTANCE;
    
    private final MapperFacade mapperFacade;
    
    private CustomerMapper() {
        BaseMapper.MAPPER_FACTORY.classMap(CustomerDTO.class, Customer.class)
                .byDefault()
                .register();
        mapperFacade = BaseMapper.MAPPER_FACTORY.getMapperFacade();
    }
    
    public Customer map(CustomerDTO customerDTO) {
        return this.mapperFacade.map(customerDTO, Customer.class);
    }
    
    public CustomerDTO map(Customer customer) {
        return this.mapperFacade.map(customer, CustomerDTO.class);
    }
}</pre><p></p>
<p>In this case I&#8217;m using two new classes: <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/domain/Customer.java" title="Customer at GitHub" target="_blank">Customer</a> and <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/dto/CustomerDTO.java" title="CustomerDTO at GitHub" target="_blank">CustomerDTO</a>.</p>
<p>Finally, just use this helper classes:</p>
<p></p><pre class="crayon-plain-tag">CustomerDTO customerDTO = new CustomerDTO();
//Setters at will
Customer customer = CustomerMapper.INSTANCE.map(customerDTO);</pre><p></p>
<h1>How it works and Customization</h1>
<p>The best way to understand how Orika works is to read the <a href="http://orika-mapper.github.io/orika-docs/faq.html" title="Orika FAQ" target="_blank">FAQ</a>, but the source code is very clear and easy to follow, just in case  you want to take a deeper look to the details.</p>
<p><em>&#8220;Orika uses reflection to investigate the metadata of the objects to be mapped and then generates byte-code at runtime which is used to map those classes [&#8230;]&#8221;</em></p>
<p><em>&#8220;Orika mapping is configured via Java code at runtime, via a fluent-style ClassMapBuilder API. An instance is obtained from a MapperFactory which is then used to describe the mapping from one type to another. Finally, the specified ClassMap is registered with the MapperFactory for later use in generating a byte-code mapper.&#8221;</em></p>
<p>To configure Orika, the author recommends to extend the ConfigurableMapper class, and I will use this approach for using Orika with Spring (see below)</p>
<p>If you want to configure the code generation, compilation and so on, see how to do this using the MapperFactory in the next topic.</p>
<h3>MapperFactory Configuration</h3>
<p>The core class <strong>MapperFactory</strong> is instantiated as you&#8217;ve seen above, by building the provided implementation: <strong>DefaultMapperFactory</strong>. It uses a set of Strategy and factory objects for resolving constructors, for compiling code (actually, they belong to its inner static class <strong>MapperFactoryBuilder</strong> that is extended by its other inner static class that you use to instantiate the MapperFactory: the <strong>Builder</strong>), for resolving properties, and specially for building class maps.</p>
<p>So you can customize all of them after calling <strong><em>Builder</em>()</strong> and before the <strong><em>build()</em></strong> method:</p>
<p></p><pre class="crayon-plain-tag">new DefaultMapperFactory.Builder()
.constructorResolverStrategy(new SimpleConstructorResolverStrategy()) //By default, you can extend it or implement your own ConstructorResolverStrategy
.compilerStrategy(new JavassistCompilerStrategy()) //By default, you can extend it, implement your own CompilerStrategy or use EclipseJdtCompilerStrategy
.propertyResolverStrategy(new IntrospectorPropertyResolver()) //By default, you can extend it or implement your own PropertyResolverStrategy
.classMapBuilderFactory(new ClassMapBuilder.Factory()) //by default. You can use //enabled by default or //enabled by default.Factory
.useAutoMapping(true) //enabled by default
.mapNulls(true) //enabled by default
.build();</pre><p></p>
<h3>Custom Mappers</h3>
<p>A <strong><em>Mapper&lt;A, B&gt;</em></strong> copies the properties from one object onto another and it&#8217;s used internally by Orika (MapperFacade, MapperGenerator and MapperFactory use it, but it isn&#8217;t really interesting for this post, actually)</p>
<p>If you want to take control of how properties of one object instance are copied to another object instance (not null), just extends the abstract class <strong><em>CustomMapper&lt;A,B&gt;</em></strong>.</p>
<p>Then, you can register your custom mapper in the <strong>MapperFactory</strong> via its method <strong><em>registerMapper(Mapper&lt;A, B&gt; mapper)</em></strong>.</p>
<p>It&#8217;s intended to be used when the mapping behavior configured via the ClassMapBuilder API doesn’t suit your purposes, but only to copy properties, that is, the destination object already exists. If you want to control instantiation, use a CustomConverter or ObjectFactory which both return an instance. See below.</p>
<p>If you need to map nested members of the given object, you can doing so by using the current <strong>MapperFacade</strong> that it&#8217;s accessible via a protected <strong><em>mapperFacade</em></strong> variable. </p>
<p>I&#8217;ve used converters in a Spring applications as components that can be scanned and used to configure the MapperFactory by extending ConfigurableMapper as I mentioned above and I&#8217;ll show below.</p>
<h3>Object Factories</h3>
<p>An <strong><em>ObjectFactory&lt;D&gt;</em></strong> instantiates objects. You can implement this interface and register your implementation in the MapperFactory via their method <strong><em>registerObjectFactory</em></strong> (there are a couple of them)</p>
<p>I&#8217;ve never used this option.</p>
<h3>Custom Converters</h3>
<p>A <strong><em>Converter&lt;S, D&gt;</em></strong> combines both ObjectFactory and Mapper together, returning a new instance of the destination type with all properties copied from the source instance.</p>
<p>When you want to take complete control over the instantiation and mapping, just extend <strong><em>CustomConverter&lt;S, D&gt;</em></strong> to create the new instance and to provide it the properties from the source object.</p>
<p>Then, you can register your custom converter in the MapperFactory by obtaining its <strong>ConverterFactory</strong> via the <strong><em>getConverterFactory()</em></strong> method and then using one of its <strong><em>registerConverter()</em></strong> methods.</p>
<p>I&#8217;ve found this option useful when you want to create some hard conversion between classes that has the same meaning in your code but are not really related in terms of Java. Well, it&#8217;s a conversion, let&#8217;s say, from a date represented in a String and a date that has to be a Calendar. You have to use some formatter for doing so.</p>
<p>It&#8217;s also very easy to configure converters as Spring components if you need so.</p>
<h1>Using Orika with Spring</h1>
<p>Since the Orika core classes <strong>MapperFactory</strong> and the <strong>MapperFacade</strong> obtained from it are very expensive to instantiate and initialize, but at the same time are thread-safe, they should be shared as singletons. That is, they are good candidates for being Spring beans with singleton scope.</p>
<p>Let&#8217;s start with using spring-framework in a maven project,just add the next dependency to the pom.xml file:</p>
<p></p><pre class="crayon-plain-tag">&lt;dependency&gt;
			&lt;groupId&gt;org.springframework&lt;/groupId&gt;
			&lt;artifactId&gt;spring-context&lt;/artifactId&gt;
			&lt;version&gt;4.1.1.RELEASE&lt;/version&gt;&lt;!-- or latest version --&gt;
		&lt;/dependency&gt;</pre><p></p>
<h3>The Spring application</h3>
<p>Let&#8217;s create a couple of beans to obtain a Person and a PersonDTO, let&#8217;s call them service and repository respectively:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.domain.Person;

public interface PersonService {
    
    public Person obtainPerson();
    
}</pre><p></p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.dto.PersonDTO;

public interface PersonRepository {
    
    public PersonDTO obtainPerson();

}</pre><p></p>
<p>And their implementations, the one for the service will use the repository interface, and the one for the repository will be a simple in-memory implementation.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.google.common.collect.ImmutableList;
import com.malsolo.orika.test.dto.PersonDTO;
import java.util.Random;
import org.springframework.stereotype.Repository;

@Repository
public class PersonRepositoryImpl implements PersonRepository {
    
    Random random = new Random();

    @Override
    public PersonDTO findPerson() {
        return this.createPersonDTO(random.nextLong());
    }

    private PersonDTO createPersonDTO(long l) {
        PersonDTO dto = new PersonDTO();
        dto.setId(l);
        //More setters here
        return dto;
    }
}</pre><p></p>
<p>Note that the service will need to convert from the DTO to the domain object, so let&#8217;s inject a mapper.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.domain.Person;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl implements PersonService {
    
    @Autowired
    private PersonRepository personRepository;
    
    private MapperFacade mapper;

    @Autowired
    public void setMapperFactory(MapperFactory mapperFactory) {
        this.mapper = mapperFactory.getMapperFacade();
    }
    
    @Override
    public Person obtainPerson() {
        return mapper.map(this.personRepository.findPerson(), Person.class);
    }

}</pre><p></p>
<p>As you can see, I used setter injection (via autowiring) to provide a MapperFactory in order to obtain from it a MapperFacade. I&#8217;m using the suggestion of having the MapperFactory as singleton, that it&#8217;s easy to achieve with Spring.</p>
<p>Since MapperFactory has a particular way to be instantiated, the best option is to create a factory for exposing it, a FactoryBean:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

@Component
public class MapperFactoryFactory implements FactoryBean&lt;MapperFactory&gt; {

    @Override
    public MapperFactory getObject() throws Exception {
        return new DefaultMapperFactory.Builder().build();
    }

    @Override
    public Class&lt;?&gt; getObjectType() {
        return MapperFactory.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}</pre><p></p>
<p>This approach has been selected just in case I want to use a BoundMapperFacade, but it&#8217;s possible to use a MapperFacade directly by creating a <a href="http://github" title="title" target="_blank">MapperFacadeFactory</a>.</p>
<p>Now, let&#8217;s configure the Spring application</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class OrikaSpringTest {
    
    public static void main(String... args) {
        ApplicationContext context = 
          new AnnotationConfigApplicationContext(OrikaSpringTest.class);
        PersonService personService = context.getBean(PersonService.class);
        Person person = personService.obtainPerson();
        System.out.printf(&quot;%s\n&quot;, person.toString());
    }

}</pre><p></p>
<p>This is enough for the project to run:</p>
<p></p><pre class="crayon-plain-tag">Person{id=0, name=Name 0, surnames=null, address=null}</pre><p></p>
<p>But <strong><u>pay attention</u></strong>, the mapper didn&#8217;t work, because there are differences between the two classes (tow attributes with different names, and the same concept, address, with different types)</p>
<h3>Plugging in Orika Mappers and Converters with Spring</h3>
<p>Orika provides custom converters and mappers, so the only thing we need is to configure them as spring beans in the application context. Let&#8217;s see how to do this.</p>
<p>First, we need a custom mapper. We annotate it as component to be discovered (via component scanning) by Spring.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.domain.Address;
import com.malsolo.orika.test.domain.Person;
import com.malsolo.orika.test.dto.PersonDTO;
import ma.glasnost.orika.CustomMapper;
import ma.glasnost.orika.MappingContext;
import org.springframework.stereotype.Component;

@Component
public class PersonDtoToPersonMapper extends CustomMapper&lt;PersonDTO, Person&gt; {

    @Override
    public void mapAtoB(PersonDTO a, Person b, MappingContext context) {
        b.setId(a.getId());
        b.setName(a.getName());
        b.setSurnames(a.getLastNames());
        //I could use the protected mapperFacade if I need to map a particular field
        //this.mapperFacade.map(sourceObject, destinationClass);
        Address address = new Address();
        address.setStreet(a.getStreetAddress());
        address.setCity(a.getCity());
        address.setZipCode(a.getPostalCode());
        b.setAddress(address);
    }

    @Override
    public void mapBtoA(Person b, PersonDTO a, MappingContext context) {
        a.setId(b.getId());
        a.setName(b.getName());
        a.setLastNames(b.getSurnames());
        Address address = b.getAddress();
        if (address != null) {
            a.setStreetAddress(address.getStreet());
            a.setCity(address.getCity());
            a.setPostalCode(address.getZipCode());
        }
    }

}</pre><p></p>
<p>Finally, we have to plug in mappers and converters that belongs to the Spring application context, into the MapperFactory. If we extend <strong>ConfigurableMapper</strong> we will have a MapperFactory created for us, and later on, the chance to access the application context itself to look up for the custom mappers and converters that are Spring components to register them in the MapperFactory.</p>
<p>Let&#8217;s show the code:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import java.util.Map;
import ma.glasnost.orika.Converter;
import ma.glasnost.orika.Mapper;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class SpringConfigurableMapper extends ConfigurableMapper {

    private ApplicationContext applicationContext;

    private MapperFactory mapperFactory;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        addSpringMappers();
        addSpringConverter();
    }

    @Override
    protected void configure(MapperFactory factory) {
        super.configure(factory);
        this.mapperFactory = factory;
    }

    private void addSpringMappers() {
        @SuppressWarnings(&quot;rawtypes&quot;)
        final Map&lt;String, Mapper&gt; mappers = applicationContext
                .getBeansOfType(Mapper.class);
        for (final Mapper&lt;?, ?&gt; mapper : mappers.values()) {
            addMapper(mapper);
        }
    }

    private void addMapper(Mapper&lt;?, ?&gt; mapper) {
        this.mapperFactory.registerMapper(mapper);
    }

    private void addSpringConverter() {
        @SuppressWarnings(&quot;rawtypes&quot;)
		final Map&lt;String, Converter&gt; converters = applicationContext
                .getBeansOfType(Converter.class);
        for (final Converter&lt;?, ?&gt; converter : converters.values()) {
            addConverter(converter);
        }
    }

    private void addConverter(Converter&lt;?, ?&gt; converter) {
        this.mapperFactory.getConverterFactory().registerConverter(converter);
    }

}</pre><p></p>
<p>Some important things to note here:</p>
<ul>
<li>Our class SpringConfigurableMapper is a @Component</li>
<p>When Spring instantiates it, it will call its constructor that is inherited from <strong>ConfigurableMapper</strong> and it calls an init method that creates a MapperFactory and allows you to configure via the overriden method. </p>
<p>So, the first method called is <strong><em>configure(MapperFactory)</em></strong>.</p>
<p>Furthermore, don&#8217;t create your own MapperFactory as I did above, because it won&#8217;t be the one you&#8217;ll use to register the mappers and converters, on the contrary, this class will create a new MapperFactory.</p>
<li>Our class SpringConfigurableMapper has the ApplicationContext @Autowired</li>
<p>It&#8217;s the same as if you implement ApplicationContextAware, but I&#8217;d rather this approach.</p>
<p>Besides, it implies that the method will be called after all the beans have been created. Since you already have a MapperFactory, you can then search for custom components and converters that are spring beans and register them in the MapperFactory.</p>
<li>Our class extends ConfigurableMapper that implements MapperFacade</li>
<p>So, you have to slightly change the PersonServiceImpl and it&#8217;s better to not have a MapperFacadeFactory or you will have an autowiring exception because there would be two beans of the MapperFacade class:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import ma.glasnost.orika.MapperFacade;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.malsolo.orika.test.domain.Person;

@Service
public class PersonServiceImpl implements PersonService {
    
    @Autowired
    private PersonRepository personRepository;
    
    @Autowired
    private MapperFacade mapper;

    @Override
    public Person obtainPerson() {
        return mapper.map(this.personRepository.findPerson(), Person.class);
    }

}</pre><p></p>
<p>Now, if you run the Orika with Spring main class, <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/spring/OrikaSpringTest.java" title="Orika Spring test at GitHub" target="_blank">OrikaSpringTest</a>, everything will run as expected:</p>
<p></p><pre class="crayon-plain-tag">Person{id=85, name=Name 85, surnames=[S., Surname 85], address=Address{street=My street 85, city=City 85, zipCode=code 85}}</pre><p></p>
<h1>Resources</h1>
<ul>
<li><a href="https://github.com/jbbarquero/orika-test" title="Source code at GitHub" target="_blank">Source code</a> for this post</li>
<li><a href="http://orika-mapper.github.io/orika-docs/" title="Orika user guide" target="_blank">Orika User Guide</a></li>
<li><a href="http://kenblair.net/orika-spring-easy-bean-mapping/" title="Orika and Spring Framework = easy bean mapping" target="_blank">Orika and Spring Framework = easy bean mapping</a> by Ken Blair</li>
<li><a href="http://projects.spring.io/spring-framework/#quick-start" title="Spring Framework Quick Start" target="_blank">Spring Framework Quick Start</a></li>
<li><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#extensible-xml-meat" title="Spring Framework Reference Documentation: 35.7. Meatier examples" target="_blank">Spring Framework Reference Documentation (Meatier examples)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://malsolo.com/blog4java/?feed=rss2&#038;p=465</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Introduction to Spring Batch. Part II: more on running a Job</title>
		<link>http://malsolo.com/blog4java/?p=375</link>
		<comments>http://malsolo.com/blog4java/?p=375#comments</comments>
		<pubDate>Thu, 04 Sep 2014 15:45:23 +0000</pubDate>
		<dc:creator><![CDATA[Javier (@jbbarquero)]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Springsource]]></category>
		<category><![CDATA[JSR-352]]></category>
		<category><![CDATA[Spring Batch]]></category>
		<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://malsolo.com/blog4java/?p=375</guid>
		<description><![CDATA[In the previous blog post entry, we introduced Spring Batch with a simple exposition of its features, main concepts both for configuring and running Batch Jobs. We also saw a sample application and two ways of running it: by invoking &#8230; <a href="http://malsolo.com/blog4java/?p=375">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In the previous blog post entry, <a href="http://malsolo.com/blog4java/?p=260" title="Introduction to Spring Batch" target="_blank">we introduced Spring Batch</a> with a simple exposition of its features, main concepts both for configuring and running Batch Jobs.</p>
<p>We also saw a sample application and two ways of running it: by invoking a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobLauncher.html" title="Interface JobLauncher" target="_blank">JobLauncher</a> bean or by using <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/support/CommandLineJobRunner.html" title="Class CommandLineJobRunner" target="_blank">CommandLineJobRunner</a> from the command line.</p>
<p>In this blog entry, we&#8217;ll see two additional ways to run a Spring Batch job:</p>
<ol>
<li>Using <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobOperator.html" title="Interface JobOperator" target="_blank">JobOperator</a>, in order to have control of the batch process, from start a job to monitoring tasks such as stopping, restarting, or summarizing a Job. We&#8217;ll only pay attention to the start operation, but once a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobOperator.html" title="Interface JobOperator" target="_blank">JobOperator</a> is configured, you can use for the remaining monitoring tasks.</li>
<li>Using <a href="http://projects.spring.io/spring-boot/" title="Spring Boot" target="_blank">Spring Boot</a>, the new convention-over-configuration centric framework from the Spring team, that allows you to create with a few lines of code applications that &#8220;just run&#8221;, because Spring Boot provides a lot of features based on what you have in your classpath.</li>
</ol>
<p>As usual, all the source code is available at <a href="https://github.com/jbbarquero/spring-batch-sample" title="My Spring Batch sample at GitHub" target="_blank">GitHub</a>.</p>
<h3>Running the sample: JobOperator</h3>
<p><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobOperator.html" title="Interface JobOperator" target="_blank">JobOperator</a> is an interface that provides operations <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#JobOperator" title="JobOperator" target="_blank">for inspecting and controlling jobs</a>, mainly for a command-line client or a remote launcher like a JMX console.</p>
<p>The implementation that Spring Batch provides, <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/support/SimpleJobOperator.html" title="Class SimpleJobOperator" target="_blank">SimpleJobOperator</a>, uses <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobLauncher.html" title="Interface JobLauncher" target="_blank">JobLauncher</a>, <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/repository/JobRepository.html" title="Interface JobRepository" target="_blank">JobRepository</a>, <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/explore/JobExplorer.html" title="Interface JobExplorer" target="_blank">JobExplorer</a>, and <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/JobRegistry.html" title="Interface JobRegistry" target="_blank">JobRegistry</a> for performing its operations. They are created by the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html" title="Annotation Type EnableBatchProcessing" target="_blank">@EnableBatchProcessing</a> annotation, so we can create an <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/AdditionalBatchConfiguration.java" title="AdditionalBatchConfiguration.java" target="_blank">additional batch configuration</a> file with these dependencies autowired and later import it in the <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/BatchConfiguration.java" title="BatchConfiguration.java" target="_blank">batch configuration</a> file (not without issues, due to the way Spring loads the application context, we&#8217;ll see this shortly):</p>
<p></p><pre class="crayon-plain-tag">@Configuration
public class AdditionalBatchConfiguration {

    @Autowired
    JobRepository jobRepository;
    @Autowired
    JobRegistry jobRegistry;
    @Autowired
    JobLauncher jobLauncher;
    @Autowired
    JobExplorer jobExplorer;

    @Bean
    public JobOperator jobOperator() {
        SimpleJobOperator jobOperator = new SimpleJobOperator();
        jobOperator.setJobExplorer(jobExplorer);
        jobOperator.setJobLauncher(jobLauncher);
        jobOperator.setJobRegistry(jobRegistry);
        jobOperator.setJobRepository(jobRepository);
        return jobOperator;
    }

}</pre><p></p>
<p>And the <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/context/annotation/Import.html" title="Annotation Type Import" target="_blank">@Import</a>:</p>
<p></p><pre class="crayon-plain-tag">@Configuration
@EnableBatchProcessing
@Import(AdditionalBatchConfiguration.class)
public class BatchConfiguration {

	// Omitted

}</pre><p></p>
<p>Now it seems easy to run the job with a <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/MainJobOperator.java" title="MainJobOperator.java" target="_blank">main class</a>:</p>
<p></p><pre class="crayon-plain-tag">@Component
public class MainJobOperator {

    @Autowired
    JobOperator jobOperator;

    @Autowired
    Job importUserJob;

    public static void main(String... args) throws JobParametersInvalidException, JobInstanceAlreadyExistsException, NoSuchJobException, DuplicateJobException, NoSuchJobExecutionException {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);

        MainJobOperator main = context.getBean(MainJobOperator.class);
        long executionId = main.jobOperator.start(main.importUserJob.getName(), null);

        MainHelper.reportResults(main.jobOperator, executionId);
        MainHelper.reportPeople(context.getBean(JdbcTemplate.class));

        context.close();

        System.out.printf(&quot;\nFIN %s&quot;, main.getClass().getName());

    }
}</pre><p></p>
<p>But there&#8217;s a little problem&#8230; it doesn&#8217;t work:</p>
<p></p><pre class="crayon-plain-tag">Exception in thread "main" org.springframework.batch.core.launch.NoSuchJobException: No job configuration with the name [importUserJob] was registered
	at org.springframework.batch.core.configuration.support.MapJobRegistry.getJob(MapJobRegistry.java:66)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:483)
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
	at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
	at com.sun.proxy.$Proxy14.getJob(Unknown Source)
	at org.springframework.batch.core.launch.support.SimpleJobOperator.start(SimpleJobOperator.java:310)
	at com.malsolo.springframework.batch.sample.MainJobOperator.main(MainJobOperator.java:15)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:483)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Process finished with exit code 1</pre><p></p>
<p>The problem here, <em><font color=red>No job configuration with the name [<strong>importUserJob</strong>] was registered</font></em>, is due to the way that <a href="http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/launch/JobOperator.html#start-java.lang.String-java.lang.String-" title="API" target="_blank">JobOperator.start(String jobName, String parameters)</a> works.</p>
<p>The main difference with <a href="http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/launch/JobLauncher.html#run-org.springframework.batch.core.Job-org.springframework.batch.core.JobParameters-" title="API" target="_blank">JobLauncher.run(Job job, JobParameters jobParameters)</a> is that the former has String as parameters while the latter uses objects directly.</p>
<p>So <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobOperator.html" title="Interface JobOperator" target="_blank">JobOperator</a>, actually <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/support/SimpleJobOperator.html" title="Class SimpleJobOperator" target="_blank">SimpleJobOperator</a>, has to obtain a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/Job.html" title="Interface Job" target="_blank">Job</a> with the provided name. In order to do so, it uses the <a href="http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/configuration/JobLocator.html#getJob-java.lang.String-" title="API" target="_blank">JobRegistry.getJob(String name)</a> method. The available Spring Batch implementation is <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/support/MapJobRegistry.html" title="Class MapJobRegistry" target="_blank">MapJobRegistry</a> that uses a ConcurrentMap to store using the job name as the key, a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/JobFactory.html" title="Interface JobFactory" target="_blank">JobFactory</a> to create the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/Job.html" title="Interface Job" target="_blank">Job</a> when requested.</p>
<p>The problem is that this map has not been populated.</p>
<p>The first solution is easy: the JobRegistry allows you to register at runtime a JobFactory to later obtain the Job as explained above. So, we only need to create this JobFactory&#8230;</p>
<p></p><pre class="crayon-plain-tag">@Configuration
public class AdditionalBatchConfiguration {
//    Rest omitted
    @Autowired
    Job importUserJob;

    @Bean
    public JobFactory jobFactory() {
        return new ReferenceJobFactory(importUserJob);
    }
}</pre><p></p>
<p>&#8230;and register it in the main method:</p>
<p></p><pre class="crayon-plain-tag">@Component
public class MainJobOperator {

    @Autowired
    JobFactory jobFactory;
    @Autowired
    JobRegistry jobRegistry;
    @Autowired
    JobOperator jobOperator;

    @Autowired
    Job importUserJob;

    public static void main(String... args) throws JobParametersInvalidException, JobInstanceAlreadyExistsException, NoSuchJobException, DuplicateJobException, NoSuchJobExecutionException {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);

        MainJobOperator main = context.getBean(MainJobOperator.class);
        main.jobRegistry.register(main.jobFactory);
        long executionId = main.jobOperator.start(main.importUserJob.getName(), null);

        MainHelper.reportResults(main.jobOperator, executionId);
        MainHelper.reportPeople(context.getBean(JdbcTemplate.class));

        context.close();

        System.out.printf(&quot;\nFIN %s&quot;, main.getClass().getName());

    }
}</pre><p></p>
<p>And now it works:</p>
<p></p><pre class="crayon-plain-tag">***********************************************************
JobExecution: id=0, version=2, startTime=2014-09-04 13:03:37.964, endTime=2014-09-04 13:03:38.141, lastUpdated=2014-09-04 13:03:38.141, status=COMPLETED, exitStatus=exitCode=COMPLETED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[importUserJob]], jobParameters=[{}]
* Steps executed:
StepExecution: id=0, version=3, name=step1, status=COMPLETED, exitStatus=COMPLETED, readCount=5, filterCount=0, writeCount=5 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=1, rollbackCount=0, exitDescription=
***********************************************************
***********************************************************
* People found:

* Found firstName: JILL, lastName: DOE in the database

* Found firstName: JOE, lastName: DOE in the database

* Found firstName: JUSTIN, lastName: DOE in the database

* Found firstName: JANE, lastName: DOE in the database

* Found firstName: JOHN, lastName: DOE in the database
***********************************************************</pre><p></p>
<p>But I don&#8217;t like this approach, it&#8217;s too manual.</p>
<p>I&#8217;d rather to populate the JobRegistry automatically, and Spring Batch provides two mechanisms for doing so, <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#d4e1228" title="JobRegistryBeanPostProcessor" target="_blank">a bean post-processor</a>, <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/support/JobRegistryBeanPostProcessor.html" title="Class JobRegistryBeanPostProcessor" target="_blank">JobRegistryBeanPostProcessor</a>, and <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#d4e1233" title="AutomaticJobRegistrar" target="_blank"> a component</a> that loads and unloads Jobs by creating child context and registering  jobs from those contexts as they are created, <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/support/AutomaticJobRegistrar.html" title="Class AutomaticJobRegistrar" target="_blank">AutomaticJobRegistrar</a>.</p>
<p>We&#8217;ll see the post-processor approach, because it&#8217;s very easy. Just declare the bean in the Batch configuration and run the original main class.</p>
<p></p><pre class="crayon-plain-tag">@Configuration
@EnableBatchProcessing
@Import(AdditionalBatchConfiguration.class)
public class BatchConfiguration {

	// Omitted

    @Bean
    public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {
        JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
        jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
        return jobRegistryBeanPostProcessor;
    }

}</pre><p></p>
<p>The bean post processor has to be declared in this configuration file for registering the job when it&#8217;s created (this is the issue that I mentioned before, if you declare the post processor in another java file configuration, for instance in the <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/AdditionalBatchConfiguration.java" title="AdditionalBatchConfiguration.java" target="_blank">AdditionalBatchConfiguration</a> it will never receive the job bean). It uses the same <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/JobRegistry.html" title="Interface JobRegistry" target="_blank">JobRegistry</a> that uses the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobOperator.html" title="Interface JobOperator" target="_blank">JobOperator</a> to launch the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/Job.html" title="Interface Job" target="_blank">Job</a>. Actually the only that exists, but it&#8217;s good to know this.</p>
<p>It also works:</p>
<p></p><pre class="crayon-plain-tag">***********************************************************
JobExecution: id=0, version=2, startTime=2014-09-04 13:20:07.343, endTime=2014-09-04 13:20:07.522, lastUpdated=2014-09-04 13:20:07.522, status=COMPLETED, exitStatus=exitCode=COMPLETED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[importUserJob]], jobParameters=[{}]
* Steps executed:
StepExecution: id=0, version=3, name=step1, status=COMPLETED, exitStatus=COMPLETED, readCount=5, filterCount=0, writeCount=5 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=1, rollbackCount=0, exitDescription=
***********************************************************
***********************************************************
* People found:

* Found firstName: JILL, lastName: DOE in the database

* Found firstName: JOE, lastName: DOE in the database

* Found firstName: JUSTIN, lastName: DOE in the database

* Found firstName: JANE, lastName: DOE in the database

* Found firstName: JOHN, lastName: DOE in the database
***********************************************************</pre><p></p>
<h3>Running the sample: Spring Boot</h3>
<p>We&#8217;d like to try how quickly and easy is Spring Boot for launching Spring Batch applications once we already have a functional configuration.</p>
<p>And it seems to be a piece of cake (the problem here is to know what is happening under the hood)</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.springframework.batch.sample;
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ApplicationConfiguration.class)})
@EnableAutoConfiguration
public class MainBoot {

    public static void main(String... args) {

        ApplicationContext context = SpringApplication.run(MainBoot.class);

        MainHelper.reportPeople(context.getBean(JdbcTemplate.class));

    }
}</pre><p></p>
<p>Actually, Spring Boot is out of the bounds of this topic, it deserves its own entry (even, an entire book) but we can summarize the important code here:</p>
<ul>
<li>Line 3: <a href="http://docs.spring.io/spring-boot/docs/current/api/index.html?org/springframework/boot/autoconfigure/EnableAutoConfiguration.html" title="Annotation Type EnableAutoConfiguration" target="_blank">@EnableAutoConfiguration</a>, with this annotation you want Spring Boot to instantiate the beans that you&#8217;re going to need based on the libraries on your classpath.</li>
<li>Line 8: <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/SpringApplication.html#run(java.lang.Object[], java.lang.String[])" title="API" target="_blank">the run method</a>, to bootstrap the application by passing the class itself (in our case, <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/MainBoot.java" title="MainBoot.java" target="_blank">MainBoot</a>) that serves as the primary Spring component.
</ul>
<p>It&#8217;s enough to run the Batch application:</p>
<p></p><pre class="crayon-plain-tag">.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.4.RELEASE)

2014-09-04 16:58:55.109  INFO 15646 --- [           main] c.m.s.batch.sample.MainBoot              : Starting MainBoot on jbeneito-Latitude-3540 with PID 15646 (/home/jbeneito/Documents/git/spring-batch-sample/target/classes started by jbeneito in /home/jbeneito/Documents/git/spring-batch-sample)
2014-09-04 16:58:55.237  INFO 15646 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6366ebe0: startup date [Thu Sep 04 16:58:55 CEST 2014]; root of context hierarchy
2014-09-04 16:58:56.039  INFO 15646 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'jdbcTemplate': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=batchConfiguration; factoryMethodName=jdbcTemplate; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/malsolo/springframework/batch/sample/BatchConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=mainForSpringInfo; factoryMethodName=jdbcTemplate; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/malsolo/springframework/batch/sample/MainForSpringInfo.class]]
2014-09-04 16:58:56.691  WARN 15646 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean Javadoc for complete details
2014-09-04 16:58:56.724  WARN 15646 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean Javadoc for complete details
2014-09-04 16:58:56.729  INFO 15646 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2014-09-04 16:58:56.975  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'batchConfiguration' of type [class com.malsolo.springframework.batch.sample.BatchConfiguration$$EnhancerBySpringCGLIB$$c3ec56ab] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:57.145  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$5a15b25b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:57.238  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionAttributeSource' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:57.294  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionInterceptor' of type [class org.springframework.transaction.interceptor.TransactionInterceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:57.301  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:57.374  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'dataSourceConfiguration' of type [class com.malsolo.springframework.batch.sample.DataSourceConfiguration$$EnhancerBySpringCGLIB$$18a97d02] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:57.455  INFO 15646 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Creating embedded database 'testdb'
2014-09-04 16:58:58.156  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [schema-all.sql]
2014-09-04 16:58:58.178  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [schema-all.sql] in 20 ms.
2014-09-04 16:58:58.178  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2014-09-04 16:58:58.189  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 11 ms.
2014-09-04 16:58:58.198  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'dataSource' of type [class org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:58.206  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$DataSourceInitializerConfiguration' of type [class org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$DataSourceInitializerConfiguration$$EnhancerBySpringCGLIB$$c0608242] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:58.257  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.datasource.CONFIGURATION_PROPERTIES' of type [class org.springframework.boot.autoconfigure.jdbc.DataSourceProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:58.260  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from URL [file:/home/jbeneito/Documents/git/spring-batch-sample/target/classes/schema-all.sql]
2014-09-04 16:58:58.262  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from URL [file:/home/jbeneito/Documents/git/spring-batch-sample/target/classes/schema-all.sql] in 2 ms.
2014-09-04 16:58:58.263  WARN 15646 --- [           main] o.s.b.a.jdbc.DataSourceInitializer       : Could not send event to complete DataSource initialization (ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext@6366ebe0: startup date [Thu Sep 04 16:58:55 CEST 2014]; root of context hierarchy)
2014-09-04 16:58:58.263  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'dataSourceInitializer' of type [class org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:58.277  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration' of type [class org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$85a27e41] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:58.320  INFO 15646 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'jobRegistry' of type [class com.sun.proxy.$Proxy25] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-09-04 16:58:58.795  INFO 15646 --- [           main] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: HSQL
2014-09-04 16:58:59.056  INFO 15646 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2014-09-04 16:58:59.361  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2014-09-04 16:58:59.381  INFO 15646 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 20 ms.
2014-09-04 16:58:59.890  INFO 15646 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2014-09-04 16:58:59.926  INFO 15646 --- [           main] o.s.b.a.b.JobLauncherCommandLineRunner   : Running default command line with: []
2014-09-04 16:59:00.023  INFO 15646 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] launched with the following parameters: [{run.id=1}]
2014-09-04 16:59:00.060  INFO 15646 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
Converting (firstName: Jill, lastName: Doe) into (firstName: JILL, lastName: DOE)
Converting (firstName: Joe, lastName: Doe) into (firstName: JOE, lastName: DOE)
Converting (firstName: Justin, lastName: Doe) into (firstName: JUSTIN, lastName: DOE)
Converting (firstName: Jane, lastName: Doe) into (firstName: JANE, lastName: DOE)
Converting (firstName: John, lastName: Doe) into (firstName: JOHN, lastName: DOE)
2014-09-04 16:59:00.162  INFO 15646 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2014-09-04 16:59:00.164  INFO 15646 --- [           main] c.m.s.batch.sample.MainBoot              : Started MainBoot in 5.963 seconds (JVM running for 8.019)
***********************************************************
* People found:

* Found firstName: JILL, lastName: DOE in the database

* Found firstName: JOE, lastName: DOE in the database

* Found firstName: JUSTIN, lastName: DOE in the database

* Found firstName: JANE, lastName: DOE in the database

* Found firstName: JOHN, lastName: DOE in the database
***********************************************************
2014-09-04 16:59:00.258  INFO 15646 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6366ebe0: startup date [Thu Sep 04 16:58:55 CEST 2014]; root of context hierarchy
2014-09-04 16:59:00.262  INFO 15646 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

Process finished with exit code 0</pre><p></p>
<p>As a side note, this class already scans for compontents, so we don’t need to make an additional scan for components, so we exclude the <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/ApplicationConfiguration.java" title="ApplicationConfiguration.java" target="_blank">ApplicationConfiguration</a> class with a filter.</p>
<p>Finally, we use the <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/MainHelper.java" title="MainHelper.java" target="_blank">MainHelper</a> class to show a summary of the results.</p>
<p>That&#8217;s all for now, because one more time this entry is growing really fast. Thus, we&#8217;ll see in the next post the last topic of Spring Batch that I want to talk about: <a href="https://jcp.org/en/jsr/detail?id=352" title="JSR 352: Batch Applications for the Java Platform" target="_blank">JSR 352</a>.</p>
<h3>Resources</h3>
<ul>
<li><a href="https://www.youtube.com/watch?v=lHCPppMlylY" title="Youtube" target="_blank">Webinar: Spring Batch 3.0.0</a> by <strong>Michael Minella</strong>. Published on Jun 18, 2014.</li>
<li><a href="https://www.youtube.com/watch?v=yKs4yPs-5yU" title="youtube" target="_blank">JSR-352, Spring Batch and You</a> by <strong>Michael Minella</strong>. Published on Feb 3, 2014.</li>
<li><a href="https://www.youtube.com/watch?v=8tiqeV07XlI" title="youtube" target="_blank">Integrating Spring Batch and Spring Integration</a> by <strong>Gunnar Hillert</strong>, <strong>Michael Minella</strong>. Published on Jul 9, 2014.</li>
<li><a href="http://www.amazon.com/Pro-Spring-Batch-Experts-Voice/dp/1430234520/ref=sr_1_1?ie=UTF8&#038;qid=1409752293&#038;sr=8-1&#038;keywords=pro+spring+batch" title="Amazon" target="_blank">Pro Spring Batch (Expert&#8217;s Voice in Spring)</a> by <strong>Michael Minella</strong>. Published on July 12, 2011 by <a href="http://www.apress.com/9781430234524" title="Apress" target="_blank">Apress</a>.</li>
<li>Spring Batch in Action by <strong>Arnaud Cogoluegnes</strong>, <strong>Thierry Templier</strong>, <strong>Gary Gregory</strong>, <strong>Olivier Bazoud</strong>. Published on October 10, 2011 by <a href="http://www.manning.com/templier/" title="Manning" target="_blank">Manning Publications</a>.</li>
<li>Spring.io GETTING STARTED GUIDE: <a href="http://spring.io/guides/gs/batch-processing/" title="GETTING STARTED: Creating a Batch Service" target="_blank">Creating a Batch Service</a>.
<li><a href="http://docs.spring.io/spring-batch/trunk/reference/html/" title="Spring Batch - Reference Documentation" target="_blank">Spring Batch &#8211; Reference Documentation</a></li>
<li><a href="http://docs.spring.io/spring-batch/apidocs/index.html?overview-summary.html" title="Spring Batch 3.0.1.RELEASE API" target="_blank">Spring Batch &#8211; API specification</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://malsolo.com/blog4java/?feed=rss2&#038;p=375</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Spring Batch</title>
		<link>http://malsolo.com/blog4java/?p=260</link>
		<comments>http://malsolo.com/blog4java/?p=260#comments</comments>
		<pubDate>Wed, 03 Sep 2014 10:58:02 +0000</pubDate>
		<dc:creator><![CDATA[Javier (@jbbarquero)]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Springsource]]></category>
		<category><![CDATA[JSR-352]]></category>
		<category><![CDATA[Spring Batch]]></category>
		<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://malsolo.com/blog4java/?p=260</guid>
		<description><![CDATA[Spring Batch is the Spring Project aimed to write Java Batch applications by using the foundations of Spring Framework. Michael T. Minella, project lead of Spring Batch and also a member of the JSR 352 (Batch Applications for the Java &#8230; <a href="http://malsolo.com/blog4java/?p=260">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://projects.spring.io/spring-batch/" title="Spring Batch" target="_blank">Spring Batch</a> is the <a href="http://spring.io/projects" title="Spring Projects" target="_blank">Spring Project</a> aimed <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/DefaultBatchConfigurer.html" title="Class DefaultBatchConfigurer" target="_blank"></a>to write Java Batch applications by using the foundations of Spring Framework.</p>
<p><a href="http://spring.io/team/mminella" title="Michael Minella" target="_blank">Michael T. Minella</a>, project lead of Spring Batch and also a member of the <a href="https://jcp.org/en/jsr/detail?id=352" title="JSR 352" target="_blank">JSR 352 (Batch Applications for the Java Platform)</a> expert group, wrote in his book <a href="http://www.amazon.com/Pro-Spring-Batch-Experts-Voice/dp/1430234520" title="Pro Spring Batch" target="_blank">Pro Spring Batch</a> the next definition &#8220;<em>Batch processing [&#8230;] is defined as the processing of data without interaction or interruption. Once started, a batch process runs to some form of completion without any intervention</em>&#8220;.</p>
<p>Typically Batch Jobs are long-running, non-interactive and process large volumes of data, more than fits in memory or a single transaction. Thus they usually run outside office hours and include logic for handling errors   and restarting if necessary.</p>
<p>Spring Batch provides, among others, the next features:</p>
<ul>
<li>Transaction management, to allow you to focus on business processing.</li>
<li>Chunk based processing, to process a large value of data by dividing it in small pieces.</li>
<liDeclarative I/O, by providing readers and writers for a lot of scenarios.</li>
<li>Start/Stop/Restart/Skip/Retry capabilities, to handle non-interactive management of the process.</li>
<li>Web based administration interface (Spring Batch Admin), it provides an API for administering tasks.</li>
<li>Based on Spring framework, so it includes all the configuration options, including Dependency Injection.</li>
<li>Compliance with JSR 352: Batch Applications for the Java Platform.</li>
</ul>
<h3>Spring Batch concepts</h3>
<div id="attachment_266" style="width: 310px" class="wp-caption alignnone"><a href="http://malsolo.com/blog4java/wp-content/uploads/2014/08/spring-batch-reference-model.png"><img src="http://malsolo.com/blog4java/wp-content/uploads/2014/08/spring-batch-reference-model-300x119.png" alt="The Domain Language of Batch" width="300" height="119" class="size-medium wp-image-266" /></a><p class="wp-caption-text">Batch Stereotypes</p></div>
<ul>
<li><a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#domainJob" title="Job" target="_blank">Job</a>: an entity that encapsulates an entire batch process. It is composed of one or more ordered <strong>Steps</strong> and it has some properties such as restartability.</li>
<li><a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#domainStep" title="Step" target="_blank">Step</a>: a domain object that encapsulates an independent, sequential phase of a batch job.</li>
<li><a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#readersAndWriters" title="ItemReaders and ItemWriters and  ItemProcessors" target="_blank">Item</a>: the individual piece of data that it&#8217;s been processed.</li>
<li><a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#chunkOrientedProcessing" title="Chunk-Oriented Processing" target="_blank">Chunk</a>: the processing style used by Spring Batch: read and process the item and then aggregate until reach a number of items, called &#8220;<em>chunk</em>&#8221; that will be finally written.</li>
<div id="attachment_271" style="width: 310px" class="wp-caption alignnone"><a href="http://malsolo.com/blog4java/wp-content/uploads/2014/08/chunk-oriented-processing.png"><img src="http://malsolo.com/blog4java/wp-content/uploads/2014/08/chunk-oriented-processing-300x165.png" alt="Chunk-Oriented Processing" width="300" height="165" class="size-medium wp-image-271" /></a><p class="wp-caption-text">Chunk-Oriented Processing</p></div>
<li><a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#domainJobLauncher" title="JobLauncher" target="_blank">JobLauncher</a>: the entry point to launch Spring Batch jobs with a given set of JobParameters.</li>
<li><a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#domainJobRepository" title="JobRepository" target="_blank">JobRepository</a>: maintains all metadata related to job executions and provides CRUD operations for JobLauncher, Job, and Step implementations.</li>
</ul>
<h3>Running a Job</h3>
<p>The <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobLauncher.html" title="JobLauncher API" target="_blank">JobLauncher</a> interface has a basic implementation <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/support/SimpleJobLauncher.html" title="SimpleJobLauncher API" target="_blank">SimpleJobLauncher</a> whose only required dependency is a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/repository/JobRepository.html" title="JobRepository API" target="_blank">JobRepository</a>, in order to obtain an execution, so that you can use it for executing the Job.</p>
<div id="attachment_275" style="width: 310px" class="wp-caption alignnone"><a href="http://malsolo.com/blog4java/wp-content/uploads/2014/08/job-launcher-sequence-sync.png"><img src="http://malsolo.com/blog4java/wp-content/uploads/2014/08/job-launcher-sequence-sync-300x229.png" alt="JobLauncher" width="300" height="229" class="size-medium wp-image-275" /></a><p class="wp-caption-text">JobLauncher</p></div>
<p>You can also launch a Job asynchronously by configuring a <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/core/task/TaskExecutor.html" title="TaskExecutor API" target="_blank">TaskExecutor</a>. You can also this configuration <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#runningJobsFromWebContainer" title="Running Jobs from within a Web Container" target="_blank">for running Jobs from within a Web Container</a>.</p>
<div id="attachment_277" style="width: 310px" class="wp-caption alignnone"><a href="http://malsolo.com/blog4java/wp-content/uploads/2014/08/job-launcher-sequence-async.png"><img src="http://malsolo.com/blog4java/wp-content/uploads/2014/08/job-launcher-sequence-async-300x229.png" alt="Job launcher sequence async" width="300" height="229" class="size-medium wp-image-277" /></a><p class="wp-caption-text">Job launcher sequence async</p></div>
<p>A <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/JobLauncher.html" title="JobLauncher API" target="_blank">JobLauncher</a> uses the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/repository/JobRepository.html" title="JobRepository API" target="_blank">JobRepository</a> to create new <strong>JobExecution</strong> objects and run them.</p>
<div id="attachment_281" style="width: 310px" class="wp-caption alignnone"><a href="http://malsolo.com/blog4java/wp-content/uploads/2014/08/job-repository.png"><img src="http://malsolo.com/blog4java/wp-content/uploads/2014/08/job-repository-300x265.png" alt="Job Repository" width="300" height="265" class="size-medium wp-image-281" /></a><p class="wp-caption-text">Job Repository</p></div>
<h3>Running Jobs: concepts</h3>
<p>The main concepts related with Job execution are</p>
<div id="attachment_283" style="width: 310px" class="wp-caption alignnone"><a href="http://malsolo.com/blog4java/wp-content/uploads/2014/08/jobHeirarchyWithSteps.png"><img src="http://malsolo.com/blog4java/wp-content/uploads/2014/08/jobHeirarchyWithSteps-300x220.png" alt="Job hierarchy with steps" width="300" height="220" class="size-medium wp-image-283" /></a><p class="wp-caption-text">Job hierarchy with steps</p></div>
<ul>
<li><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/JobInstance.html" title="JobInstance API" target="_blank">JobInstance</a>: a logical run of a Job.</li>
<li><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/JobParameter.html" title="JobParameter API" target="_blank">JobParameters</a>: a set of parameters used to start a batch job. It categorizes each JobInstance.</li>
<li><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/JobExecution.html" title="JobExecution API" target="_blank">JobExecution</a>: physical runs of Jobs, in order to know what happens with the execution.</li>
<li><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/StepExecution.html" title="StepExecution API" target="_blank">StepExecution</a>: a single attempt to execute a Step, that is created each time a Step is run and it also provides information regarding the result of the processing.</li>
<li><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/item/ExecutionContext.html" title="ExecutionContext API" target="_blank">ExecutionContext</a>: a collection of key/value pairs that are persisted and controlled by the framework in order to allow developers a place to store persistent state that is scoped to a StepExecution or JobExecution.</li>
</ul>
<h3>Sample application</h3>
<p>Now we are going to see a simple sample application that reads a POJO that represents a Person from a file containing People data and after processing each  of them, that is just uppercase its attributes, saving them in a database.</p>
<p>All the code is available at <a href="https://github.com/jbbarquero/spring-batch-sample" title="My Spring Batch sample at GitHub" target="_blank">GitHub</a>. </p>
<p>Let&#8217;s begin with the basic domain class: <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/Person.java" title="Person.java" target="_blank">Person</a>, just a POJO.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.springframework.batch.sample;

public class Person {
    private String lastName;
    private String firstName;
    //...
}</pre><p></p>
<p>Then, let&#8217;s see the simple processor, <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/PersonItemProcessor.java" title="PersonItemProcessor.java" target="_blank">PersonItemProcessor</a>. It implements an <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/item/ItemProcessor.html" title="ItemProcessor API" target="_blank">ItemProcessor</a>, with a Person both as Input and Output.</p>
<p>It provides a method to be overwritten, <strong>process</strong>, that allows you to write the custom transformation.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.springframework.batch.sample;

import org.springframework.batch.item.ItemProcessor;

public class PersonItemProcessor implements ItemProcessor&lt;Person, Person&gt; {

    @Override
    public Person process(final Person person) throws Exception {
        final String firstName = person.getFirstName().toUpperCase();
        final String lastName = person.getLastName().toUpperCase();

        final Person transformedPerson = new Person(firstName, lastName);

        System.out.println(&quot;Converting (&quot; + person + &quot;) into (&quot; + transformedPerson + &quot;)&quot;);

        return transformedPerson;
    }

}</pre><p></p>
<p>Once done this, we can proceed to configure the Spring Batch Application, for doing so, we&#8217;ll use Java Annotations in a <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/BatchConfiguration.java" title="BatchConfiguration.java" target="_blank">BatchConfiguration</a> file:</p>
<p></p><pre class="crayon-plain-tag">// Imports and package omitted
@Configuration
@EnableBatchProcessing
@Import(AdditionalBatchConfiguration.class)
public class BatchConfiguration {

	// Input, processor, and output definition
	
	@Bean
    public ItemReader&lt;Person&gt; reader() {
		FlatFileItemReader&lt;Person&gt; reader = new FlatFileItemReader&lt;Person&gt;();
		reader.setResource(new ClassPathResource(&quot;sample-data.csv&quot;));
		reader.setLineMapper(new DefaultLineMapper&lt;Person&gt;() {{
			setLineTokenizer(new DelimitedLineTokenizer() {{
				setNames(new String[] {&quot;firstName&quot;, &quot;lastName&quot;});
			}});
			setFieldSetMapper(new BeanWrapperFieldSetMapper&lt;Person&gt;() {{
				setTargetType(Person.class);
			}});
			
		}});
		return reader;
	}
	
	@Bean
    public ItemProcessor&lt;Person, Person&gt; processor() {
        return new PersonItemProcessor();
    }
	
	@Bean
    public ItemWriter&lt;Person&gt; writer(DataSource dataSource) {
		JdbcBatchItemWriter&lt;Person&gt; writer = new JdbcBatchItemWriter&lt;Person&gt;();
		writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider&lt;Person&gt;());
		writer.setSql(&quot;INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)&quot;);
		writer.setDataSource(dataSource);
		return writer;
	}
	
	//  Actual job configuration
	
	@Bean
    public Job importUserJob(JobBuilderFactory jobs, Step s1) {
		return jobs.get(&quot;importUserJob&quot;)
				.incrementer(new RunIdIncrementer())
				.flow(s1)
				.end()
				.build();
	}
	
	@Bean
    public Step step1(StepBuilderFactory stepBuilderFactory, ItemReader&lt;Person&gt; reader,
            ItemWriter&lt;Person&gt; writer, ItemProcessor&lt;Person, Person&gt; processor) {
		return stepBuilderFactory.get(&quot;step1&quot;)
				.&lt;Person, Person&gt; chunk(10)
				.reader(reader)
				.processor(processor)
				.writer(writer)
				.build();
	}
	
	@Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
	
}</pre><p></p>
<p>Highlights for this class are:</p>
<ul>
<li>Line 2: <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/context/annotation/Configuration.html" title="Configuration API" target="_blank">@Configuration</a>, this class will be processed by the <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-java-basic-concepts" title="Java-based container configuration, basic concepts." target="_blank">Spring container to generate bean definitions</a>.</li>
<li>Line 3: <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html" title="EnableBatchProcessing API" target="_blank">@EnableBatchProcessing</a>, provides a base configuration for building batch jobs <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#javaConfig" title="Spring Batch Java Config" target="_blank">by creating the next beans beans available to be autowired</a>:
<ul>
<li>JobRepository &#8211; bean name &#8220;jobRepository&#8221;</li>
<li>JobLauncher &#8211; bean name &#8220;jobLauncher&#8221;</li>
<li>JobRegistry &#8211; bean name &#8220;jobRegistry&#8221;</li>
<li>PlatformTransactionManager &#8211; bean name &#8220;transactionManager&#8221;</li>
<li>JobBuilderFactory &#8211; bean name &#8220;jobBuilders&#8221;</li>
<li>StepBuilderFactory &#8211; bean name &#8220;stepBuilders&#8221;</li>
</ul>
<p>We&#8217;ll see shortly how it works.</li>
<li>Line 10: the <strong>reader bean</strong>, an instance of a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/item/file/FlatFileItemReader.html" title="Class FlatFileItemReader&lt;T&gt;" target="_blank">FlatFileItemReader</a>, that implements the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/item/ItemReader.html" title="Interface ItemReader&lt;T&gt;" target="_blank">ItemReader</a> interface to read each <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/Person.java" title="Person.java" target="_blank">Person</a> from the file containing people. Spring Batch provides several implementations for this interface, being this implementation that read lines from one Resource one of them.You know, <u>no need of custom code</u>.</li>
<li>Line 26: the <strong>processor bean</strong>, an instance of the previously defined <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/PersonItemProcessor.java" title="PersonItemProcessor.java" target="_blank">PersonItemProcessor</a>. See above.</li>
<li>Line 31: the <strong>writer bean</strong>, an instance of a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/item/database/JdbcBatchItemWriter.html" title="Class JdbcBatchItemWriter&lt;T&gt;" target="_blank">JdbcBatchItemWriter</a>, that implements the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/item/ItemWriter.html" title="Interface ItemWriter&lt;T&gt;" target="_blank">ItemWriter interface</a> to write the People already processed to the database. It&#8217;s also an implementation provided by Spring Batch, so <u>no need of custom code</u> again. In this case, you only have to provide an SQL, and a callback for the parameters. Since we are using named parameters, we&#8217;ve chosen a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/item/database/BeanPropertyItemSqlParameterSourceProvider.html" title="Class BeanPropertyItemSqlParameterSourceProvider&lt;T&gt;" target="_blank">BeanPropertyItemSqlParameterSourceProvider</a>. This bean also needs a DataSource, so we provided it by passing one as a method parameter in order to Spring inject the instance that it has registered.</li>
<li>Line 42: a <strong><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/Job.html" title="Interface Job" target="_blank">Job</a> bean</strong>, that it&#8217;s built using the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/JobBuilderFactory.html" title="Class JobBuilderFactory" target="_blank">JobBuilderFactory</a> that is autowired by passing it as method parameter for this @Bean method. When you call its get method, Spring Batch will create a <strong>job builder</strong> and will initialize its job repository, the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/job/builder/JobBuilder.html" title="Class JobBuilder" target="_blank">JobBuilder</a> is the convenience class for building jobs of various kinds as you can see in the code above. We also use a <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/Step.html" title="Interface Step" target="_blank">Step</a> that is configured as the next Spring bean.</li>
<li>Line 51: a <strong><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/Step.html" title="Interface Step" target="_blank">Step</a> bean</strong>, that it’s built using the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/StepBuilderFactory.html" title="Class StepBuilderFactory" target="_blank">StepBuilderFactory</a> that is autowired by passing it as method parameter for this @Bean method, as well as the other dependencies: the <strong>reader</strong>, the <strong>processor</strong> and the <strong>writer</strong> previously defined. When calling the get method from the StepBuilderFactory, Spring Batch will create a step builder and will initialize its job repository and transaction manager, the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/step/builder/StepBuilder.html" title="Class StepBuilder" target="_blank">StepBuilder</a> is an entry point for building all kinds of steps as you can see in the code above.
</ul>
<p>This configuration is almost everything needed to configure a Batch process as defined in the concepts above.</p>
<p>Actually, only one configuration class needs to have the @EnableBatchProcessing annotation in order to have the base configuration for building batch jobs. Then you can define the job with their steps and the readers/processors/writers that they need.</p>
<p>But an additional data source is needed to be used by the <strong>JobRepository</strong>. For this sample we&#8217;ll use an in-memory one:</p>
<p></p><pre class="crayon-plain-tag">@Configuration
public class DataSourceConfiguration {

    @Bean
    public DataSource dataSource() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder
                .setType(HSQL)
                .addScript(&quot;schema-all.sql&quot;)
                .addScript(&quot;org/springframework/batch/core/schema-hsqldb.sql&quot;)
                .build();
    }

}</pre><p></p>
<p>In this case we&#8217;ll use the same in-memory database, HSQL, with the schema for the application (line 9) and the schema for the job repository (line 10). The former is available as a resource of the application, the file called <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/resources/schema-all.sql" title="src/main/resources/schema-all.sql" target="_blank">schema-all.sql</a>, and the latter in the spring-batch-core jar (spring-batch-core-3.0.1.RELEASE.jar at the time of this writing)</p>
<h3>Alternate Configuration</h3>
<p>The official documentation shows an slightly different <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#javaConfig" title="Java Config" target="_blank">configuration</a> by using the <a href="http://docs.spring.io/spring/docs/4.0.6.RELEASE/javadoc-api/index.html?org/springframework/beans/factory/annotation/Autowired.html" title="Annotation Type Autowired" target="_blank">@Autowired</a> annotation for the beans that <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/step/builder/StepBuilder.html" title="Annotation Type EnableBatchProcessing" target="_blank">@EnableBatchProcessing</a> will create. Use the one that you like most. In this case they also imports the data base configuration.</p>
<p></p><pre class="crayon-plain-tag">@Configuration
@EnableBatchProcessing
@Import(DataSourceConfiguration.class)
public class AppConfig {

    @Autowired
    private JobBuilderFactory jobs;

    @Autowired
    private StepBuilderFactory steps;

    // Input, processor, and output definition omitted

    @Bean
    public Job importUserJob() {
        return jobs.get(&quot;importUserJob&quot;).incrementer(new RunIdIncrementer()).flow(step1()).end().build();
    }

    @Bean
    protected Step step1(ItemReader&lt;Person&gt; reader, ItemProcessor&lt;Person, Person&gt; processor, ItemWriter&lt;Person&gt; writer) {
        return steps.get(&quot;step1&quot;)
            .&lt;Person, Person&gt; chunk(10)
            .reader(reader)
            .processor(processor)
            .writer(writer)
            .build();
    }

}</pre><p></p>
<p>We chose another approach: we load it when configuring the application in the main method as you&#8217;ll see shortly. besides, we imported an additional batch configuration (see line 28 at <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/BatchConfiguration.java" title="BatchConfiguration.java" target="_blank">BatchConfiguration.java</a>) to provide an alternate way to launch the application.</p>
<h3>Enable Batch Processing: how it works</h3>
<p>As we said before, we will go a little deeper in how the annotation <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html" title="EnableBatchProcessing API" target="_blank">@EnableBatchProcessing</a> works.</p>
<p>To remind its goal, this annotation provides a base configuration for building batch jobs by creating a list of beans available to be autowired. An extract of the source code gives us a lot of information:</p>
<p></p><pre class="crayon-plain-tag">@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(BatchConfigurationSelector.class)
public @interface EnableBatchProcessing {

	/**
	 * Indicate whether the configuration is going to be modularized into multiple application contexts. If true then
	 * you should not create any &amp;#64;Bean Job definitions in this context, but rather supply them in separate (child)
	 * contexts through an {@link ApplicationContextFactory}.
	 */
	boolean modular() default false;

}</pre><p></p>
<p>As you can see at line 4, this annotation <a href="http://docs.spring.io/spring/docs/4.0.6.RELEASE/javadoc-api/index.html?org/springframework/context/annotation/Import.html" title="Annotation Type Import" target="_blank">imports</a> an implementation of an <a href="http://docs.spring.io/spring/docs/4.0.6.RELEASE/javadoc-api/index.html?org/springframework/context/annotation/ImportSelector.html" title="Interface ImportSelector" target="_blank">ImportSelector</a>, one of the options to import beans in a configuration class, in particular, to selective import beans according to certain criteria.</p>
<p>This particular implementation, <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/BatchConfigurationSelector.html" title="Class BatchConfigurationSelector" target="_blank">BatchConfigurationSelector</a>, instantiates the expected beans for providing common structure for enabling and using Spring Batch based in the EnableBatchProcessing&#8217;s attribute <strong>modular</strong>.</p>
<p>There are two implementations depending on whether you want the configuration to be modularized into multiple application contexts so that they don’t interfere with each other with the naming and the uniqueness of beans (for instance, beans named <strong>reader</strong>) or not. They are <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/ModularBatchConfiguration.html" title="Class ModularBatchConfiguration" target="_blank">ModularBatchConfiguration</a> and <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.html" title="Class SimpleBatchConfiguration" target="_blank">SimpleBatchConfiguration</a> respectively. Mainly they both do the same, but the former using an <a href="AutomaticJobRegistrar" title="Class AutomaticJobRegistrar" target="_blank">AutomaticJobRegistrar</a> which is responsible for creating separate <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/context/ApplicationContext.html" title="Interface ApplicationContext" target="_blank">ApplicationContext</a>s for register isolated jobs that are later accesible via the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/JobRegistry.html" title="nterface JobRegistry" target="_blank">JobRegistry</a>, and the latter just creates the main components as lazy proxies that only initialize when a method is called (in order to prevent configuration cycles)</p>
<p>The key concept here is that both extends <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/AbstractBatchConfiguration.html" title="Class AbstractBatchConfiguration" target="_blank">AbstractBatchConfiguration</a> that uses the core interface for this configuration: <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/BatchConfigurer.html" title="Interface BatchConfigurer" target="_blank">BatchConfigurer</a>.</p>
<p>The default implementation, <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/configuration/annotation/DefaultBatchConfigurer.html" title="Class DefaultBatchConfigurer" target="_blank">DefaultBatchConfigurer</a>, provides the beans mentioned above (jobRepository, jobLauncher, jobRegistry, transactionManager, jobBuilders and stepBuilders), for doing so it <u>doesn&#8217;t require a dataSource</u>, it&#8217;s Autowired with required to false, so it will use a Map based JobRepository if its dataSource is null, but you have take care if you have a dataSource eligible for autowiring that doesn&#8217;t contain the expected database schema for the job repository: the batch process will fail in this case.</p>
<p>Spring Boot provides another implementation, <a href="http://docs.spring.io/spring-boot/docs/current/api/index.html?org/springframework/boot/autoconfigure/batch/BasicBatchConfigurer.html" title="Class BasicBatchConfigurer" target="_blank">BasicBatchConfigurer</a>, but this is out of the scope of this entry.</p>
<p>With all this information, we already have a Spring Batch application configured, and we more or less know how this configuration is achieved using Java.</p>
<p>Now it&#8217;s time to run the application. </p>
<h3>Running the sample: JobLauncher</h3>
<p>We have all we need to launch a batch job, the Job to be launched and a JobLauncher, so wait no more and execute this main class: <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/MainJobLauncher.java" title="MainJobLauncher.java" target="_blank">MainJobLauncher</a>.</p>
<p></p><pre class="crayon-plain-tag">@Component
public class MainJobLauncher {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job importUserJob;

    public static void main(String... args) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);

        MainJobLauncher main = context.getBean(MainJobLauncher.class);

        JobExecution jobExecution = main.jobLauncher.run(main.importUserJob, new JobParameters());

        MainHelper.reportResults(jobExecution);
        MainHelper.reportPeople(context.getBean(JdbcTemplate.class));

        context.close();

    }

}</pre><p></p>
<p>First things first. This is the way I like to write main classes. Some people from Spring are used to writing main classes annotated with <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/context/annotation/Configuration.html" title="Annotation Type Configuration" target="_blank">@Configuration</a>, but I&#8217;d rather to annotate them as <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/stereotype/Component.html" title="Annotation Type Component" target="_blank">@Component</a>s in order to separate the actual application and its configuration from the classes that test the functionality.</p>
<p>As Spring component (line 1), it only needs to have the dependencies <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/beans/factory/annotation/Autowired.html" title="Annotation Type Autowired" target="_blank">@Autowired</a>.</p>
<p>That&#8217;s the reason for the <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/ApplicationConfiguration.java" title="ApplicationConfiguration.java" target="_blank">ApplicationConfiguration</a> class. It&#8217;s a <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/context/annotation/Configuration.html" title="Annotation Type Configuration" target="_blank">@Configuration</a> class that also performs a @ComponentScan from its own package, that will find the very <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/MainJobLauncher.java" title="MainJobLauncher.java" target="_blank">MainJobLauncher</a> and the remain <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/context/annotation/Configuration.html" title="Annotation Type Configuration" target="_blank">@Configuration</a> classes, because they are also <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/stereotype/Component.html" title="Annotation Type Component" target="_blank">@Component</a>s: <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/BatchConfiguration.java" title="BatchConfiguration.java" target="_blank">BatchConfiguration</a> and <a href="https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/DataSourceConfiguration.java" title="DataSourceConfiguration.java" target="_blank">DataSourceConfiguration</a>.  </p>
<p>As a main class, it creates the Spring Application Context (line 12), it gets the component as a Spring bean (line 14) and then it uses its methods (or attributes in this example. Line 16)</p>
<p>Let&#8217;s back to the Batch application: the line 16 is the call to the JobLauncher that will run the Spring Batch process.</p>
<p>The remaining lines are intended to show the results, both from the job execution and the results in the database.</p>
<p>It will be something like this:</p>
<p></p><pre class="crayon-plain-tag">***********************************************************
importUserJob finished with a status of  (COMPLETED).
* Steps executed:
	step1 : exitCode=COMPLETED;exitDescription=
StepExecution: id=0, version=3, name=step1, status=COMPLETED, exitStatus=COMPLETED, readCount=5, filterCount=0, writeCount=5 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=1, rollbackCount=0
***********************************************************

***********************************************************
* People found:

* Found firstName: JILL, lastName: DOE in the database

* Found firstName: JOE, lastName: DOE in the database

* Found firstName: JUSTIN, lastName: DOE in the database

* Found firstName: JANE, lastName: DOE in the database

* Found firstName: JOHN, lastName: DOE in the database
***********************************************************</pre><p></p>
<h3>Running the sample: CommandLineJobRunner</h3>
<p><a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/launch/support/CommandLineJobRunner.html" title="Class CommandLineJobRunner" target="_blank">CommandLineJobRunner</a> is a main class provided by Spring Batch as the primary entry point to <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#commandLineJobRunner" title="The CommandLineJobRunner" target="_blank">launch a Spring Batch Job</a>.</p>
<p>It requires at least two arguments: <strong>JobConfigurationXmlPath/JobConfigurationClassName</strong> and <strong>jobName</strong>. With the first, it will create an <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/context/ApplicationContext.html" title="Interface ApplicationContext" target="_blank">ApplicationContext</a> by loading a Java Configuration from a class with the same name or by loading an XML Configuration file with the same name.</p>
<p>It has a <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#domainJobLauncher" title="JobLauncher" target="_blank">JobLauncher</a> attribute that is autowired with the application context via its <a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/beans/factory/config/AutowireCapableBeanFactory.html" title="Interface AutowireCapableBeanFactory" target="_blank">AutowireCapableBeanFactory</a> exposed, that is used to autowire the bean properties by type.</p>
<p>It accepts some options (&#8220;-restart&#8221;, &#8220;-next&#8221;, &#8220;-stop&#8221;, &#8220;-abandon&#8221;) as well as parameters for the <a href="http://docs.spring.io/spring-batch/trunk/reference/htmlsingle/#domainJobLauncher" title="JobLauncher" target="_blank">JobLauncher</a> that are converted with the <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/converter/DefaultJobParametersConverter.html" title="Class DefaultJobParametersConverter" target="_blank">DefaultJobParametersConverter</a> as <a href="http://docs.spring.io/spring-batch/apidocs/index.html?org/springframework/batch/core/converter/JobParametersConverter.html" title="Interface JobParametersConverter" target="_blank">JobParametersConverter</a> that expects a &#8216;name=value&#8217; format.</p>
<p>You can declare this main class in the manifest file, directly or using some maven plugin as maven-jar-plugin, maven-shade-plugin or even exec-maven-plugin.</p>
<p>That is, you can invoke from your command line something like this:</p>
<p><strong>$ java CommandLineJobRunner job.xml jobName parameter=value</strong></p>
<p>Well, the sample code is a maven project that you can install (it&#8217;s enough if you package the application) and it allows to manage the dependencies (the mvn dependency:copy-dependencies command copies all the dependencies in the target/dependency directory)</p>
<p>To simplify, I&#8217;ll also copy the generated jar to the same directory of the dependencies in order to invoke the java command more easily:</p>
<p></p><pre class="crayon-plain-tag">~/Documents/git/spring-batch-sample$mvn clean install
[INFO] Scanning for projects...
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
...
~/Documents/git/spring-batch-sample$ mvn dependency:copy-dependencies
[INFO] Scanning for projects...
...
[INFO] Copying spring-batch-core-3.0.1.RELEASE.jar to ~/Documents/git/spring-batch-sample/target/dependency/spring-batch-core-3.0.1.RELEASE.jar
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
...
~/Documents/git/spring-batch-sample$ cp target/spring-batch-sample-0.0.1-SNAPSHOT.jar ./target/dependency/
~/Documents/git/spring-batch-sample$ java -classpath "./target/dependency/*" org.springframework.batch.core.launch.support.CommandLineJobRunner com.malsolo.springframework.batch.sample.ApplicationConfiguration importUserJob
...
12:32:17.039 [main] INFO  o.s.b.c.l.support.SimpleJobLauncher 
- Job: [FlowJob: [name=importUserJob]] 
completed with the following parameters: [{}] 
and the following status: [COMPLETED]
...</pre><p></p>
<p>That&#8217;s all for now.</p>
<p>Since this entry is becoming very large, I&#8217;ll explain other ways to run Spring Batch Jobs in a next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://malsolo.com/blog4java/?feed=rss2&#038;p=260</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Just for fun: trying the best 3 IDEs for Java</title>
		<link>http://malsolo.com/blog4java/?p=228</link>
		<comments>http://malsolo.com/blog4java/?p=228#comments</comments>
		<pubDate>Fri, 08 Aug 2014 12:52:45 +0000</pubDate>
		<dc:creator><![CDATA[Javier (@jbbarquero)]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Springsource]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[Spring Tool Suite]]></category>
		<category><![CDATA[STS]]></category>

		<guid isPermaLink="false">http://malsolo.com/blog4java/?p=228</guid>
		<description><![CDATA[Not only for fun. It&#8217;s also to open my mind. Introduction Since a few years ago, I try to use several OS in order to improve my computing skills: Windows 7/Vista, OS X (Lion currently) and my favorite Linux distribution, &#8230; <a href="http://malsolo.com/blog4java/?p=228">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Not only for fun. It&#8217;s also to open my mind.</p>
<h3>Introduction</h3>
<p>Since a few years ago, I try to use several OS in order to improve my computing skills: Windows 7/Vista, OS X (Lion currently) and my favorite Linux distribution, Ubuntu (Sheldon Cooper dixit). You can also include Android (my wife&#8217;s smartphone) and iOS (my iPhone and our iPad)</p>
<p>Suddenly, I realize that I&#8217;ve been enriched, and you’re able to do a lot of more things because you have your mind really prepared for thinking instead of conditioned by a single line of sight.</p>
<p>I observed the same improvement when I began to use Maven for Java development. I didn&#8217;t quit my IDE, but regarding compilation, the important things are the source code and bytecode. You shouldn&#8217;t think about settings, preferences, project configuration and some other artificial stuff that the IDE needs, but that is not your concern.</p>
<p>So I&#8217;ve decided to try the 3 most popular IDEs for Java currently available.</p>
<h3>Context</h3>
<p>During the last 2 months, I&#8217;ve been changing between projects I work in more quickly than I used to be accustomed, and that has allowed me to choose the IDE for working.</p>
<p>The title says it&#8217;s been for fun, but I&#8217;m using them in professional environment. Besides, the goal is not to decide which is better (it&#8217;s hard to be that rude with the others) or worst (well, it seems it&#8217;s an easy decision, because the worst Java IDE is <strong>JDeveloper</strong>, doubtless). What I want to find out is which of them is more productive for me.</p>
<p>Let&#8217;s see the first impressions.</p>
<h3>Eclipse</h3>
<p>Actually I don&#8217;t use Eclipse, but <a href="http://spring.io/tools/sts" title="Spring Tool Suite" target="_blank">Spring Tool Suite</a>, <em>&#8220;an Eclipse-based development environment that is customized for developing Spring applications&#8221;</em>. You know, Eclipse on Spring steroids.</p>
<p><u>I&#8217;ve been using Eclipse as my main IDE for years</u>, even before it was released (Visual Age for Java was the IDE that I used in my first professional project). Thus, I&#8217;m very used to writing programs with Eclipse. </p>
<p>The version that I&#8217;m currently using is 3.6.0, that is based on Eclipse 4.4 (Luna)</p>
<p>Let&#8217;s summarize my first impressions:</p>
<p>Pros:</p>
<ul>
<li>It comes in a compressed file, no native installer. That allows me to place the program in the same location on every OS (in my case, an Application folder within my user home)</li>
<li>The shortcut keys</li>
<li>Typing assistant. I love to type &#8220;main&#8221; and have an entire main method written, or &#8220;sysout&#8221; and obtain a complete log sentence.</li>
<li>The view and the perspectives is the most interesting way of organizing the IDE</li>
</ul>
<p>Cons:</p>
<ul>
<li>It crashes from time to time. Annoying.</li>
<li>It seems to consume a lot of memory</li>
<li>The TC server that it includes is based on Tomcat 7, so it doesn&#8217;t recognize Servlet 3.1 projects</li>
<li>A custom way of building code. No native support for tools like maven, gradle or ant. There are appropriate plugins, but having to update Eclipse projects to reflect maven changes is somewhat annoying</li>
<li>On Ubuntu and on OS X, the icon in the Docker runs the previously installed 3.5.1 version. Maybe is the OS fault, due to the lack of installation.
</ul>
<h3>NetBeans</h3>
<p>I&#8217;m talking about <a href="https://netbeans.org/" title="NetBeans 8.0" target="_blank">NetBeans 8.0</a>.</p>
<p>It&#8217;s hard for me to evaluate Eclipse, because it is the IDE that I use on a daily basis since a long years ago.</p>
<p>On the other hand, it&#8217;s very easy to describe the first impressions with NetBeans.</p>
<p>The installer works fine and the application runs smoothly, but I miss the way Eclipse are organized and its shortcuts (delete line: Ctrl/Cmd+D vs Ctrl/Cmd+E)</p>
<p>However <u>NetBeans is likely the best among the three IDEs</u> (not so hard to decide, apparently)</p>
<p>I got used to NetBeans in a few hours. Yes, hours. NetBeans has the more natural appearance for programming.</p>
<p>Actually, it includes all the options that Eclipse has, but sometimes with different key combination.</p>
<p>Besides, NetBeans is pure Java using external tools for compiling (maven, for instance)</p>
<p>Furthermore, it comes with Tomcat and GlassFish and a several of useful tools easy to configure with pluggins.</p>
<p>Does it have flaws? Of course, sometimes it get locked in a long wait operation and you can do nothing but wait.</p>
<p>Another tricky issue is that it uses an external tool to compile, maven for instance, so the program doesn&#8217;t exist until the project is built and neither you have the dependencies until maven downloads them. But worst than that is, if you compile successfully, but later on you introduce a compilation error, when you execute again, it runs the previously compiled version, because the current can&#8217;t be compiled due to the error.</p>
<p>Eclipse shows you an alert if there are compilation errors in your project before executing it.</p>
<h3>IntelliJ IDEA</h3>
<p>I&#8217;m sure that this is the best IDE ever, it seems so, but it makes me a little bit unproductive.</p>
<p>Eclipse is some kind of a de facto standard, and NetBeans is an easy to use program. But thanks to <a href="http://www.jetbrains.com/idea/" title="IntelliJ IDEA 13.1" target="_blank">IntelliJ IDEA 13.1</a>, the JetBrains Web Help has been the most visited page this week.</p>
<p>Besides, I don&#8217;t know what is doing the IDE. I don&#8217;t know whether the files are saved automatically, I don&#8217;t know when compilation is performed, and so on.</p>
<p>The worst thing in my humble opinion is that it doesn&#8217;t have any application server in the community edition. Please, at least Tomcat. But it has not.</p>
<p>Regarding shortcuts, it uses Ctrl/Cmd+Y for deleting lines, seriously?, the universal shortcut for “redo”? Yepes. And the rest of shortcut keys are really hard to do (Ctrl+F4 for closing a file)</p>
<p>I will try it later again, but currently it&#8217;s not my preferred choice.</p>
<p>However, once you discover how to use it, it&#8217;s the one that runs better. It seems not consume a lot of memory and it never blocks nor has crashes.</p>
<p>On Ubuntu, I have to start it via command line.</p>
<h3>Summary</h3>
<p>Of course the three programs are very good IDEs, but one by one:</p>
<ul>
<li>I feel a little bit lost with IntelliJ IDEA. It&#8217;s great but it&#8217;s hard to find the standard options.</li>
<li>I love Eclipse and its shortcut keys, and I don&#8217;t care its flaws because I&#8217;m used to them after all these years. It will be my preferred IDE for a while, but NetBeans is now here.</li>
<li>I didn&#8217;t like NetBeans, but the version 8 is a great program. It doesn&#8217;t matter if you haven&#8217;t use it before, is a very natural program. It makes Java development the way it has to be. Now I like it a lot.</li>
</ul>
<p>Some final words: they are all very good and easy to use for Java debugging. And I&#8217;m glad now I can use any of them if I had to.</p>
<p>An alternative for short projects is a text editor (Sublime Text, for instance) and a good build tool (maven or gradle, as you wish)</p>
<p>I have to try Web Based IDEs, <a href="http://nerds-central.blogspot.co.uk/2014/08/10-kickass-software-technologies.html" title="10 Kickass (software) Technologies - Gauntlet Picked Up" target="_blank">as Alexander J Turner suggested</a>.</p>
<p>That&#8217;s all for now.</p>
]]></content:encoded>
			<wfw:commentRss>http://malsolo.com/blog4java/?feed=rss2&#038;p=228</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Improving Java EE skills (including Spring)</title>
		<link>http://malsolo.com/blog4java/?p=79</link>
		<comments>http://malsolo.com/blog4java/?p=79#comments</comments>
		<pubDate>Fri, 18 Jul 2014 08:28:22 +0000</pubDate>
		<dc:creator><![CDATA[Javier (@jbbarquero)]]></dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Springsource]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://malsolo.com/blog4java/?p=79</guid>
		<description><![CDATA[A friend of mine has requested me some help for improving his skills in Java EE and Spring Framework. An exciting question, indeed. The general context He&#8217;s working for a company since 2008. To work for a company for a &#8230; <a href="http://malsolo.com/blog4java/?p=79">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>A friend of mine has requested me some help for improving his skills in Java EE and Spring Framework.</p>
<p>An exciting question, indeed.</p>
<h4>The general context</h4>
<p>He&#8217;s working for a company since 2008. To work for a company for a long time has a lot of pros, but a couple of drawbacks, being one of them a little bit worrying: the chance of obsolescence.</p>
<p>If you&#8217;re using the same environment along the years, let&#8217;s say <a href="http://www-01.ibm.com/software/websphere/solutions/" title="IBM WebSphere" target="_blank">IBM products</a>, you&#8217;ll loose the chance to discover other approaches, for instance <a href="http://www.oracle.com/us/products/middleware/cloud-app-foundation/weblogic/suite/overview/index.html" title="Oracle WebLogic" target="_blank">Oracle solutions</a>, or even better, <a href="http://projects.apache.org/" title="The Apache Software Foundation Projects" target="_blank">open source projects</a>.</p>
<p>Even worst, if the company are not willing to upgrade their products (that is very reasonable if there are budget concerns) or their libraries (that is really unwise, or the direct consequence that you don&#8217;t have a good testing process) suddenly you find yourself that you&#8217;re out of the market.</p>
<p>This is not really a problem as long as your current technology is the best technology for your needs, but sooner or later you have to face to the <a href="http://en.wikipedia.org/wiki/Technical_debt" title="Technical debt from Wikipedia" target="_blank">technical debt</a> (a really <a href="http://martinfowler.com/bliki/TechnicalDebt.html" title="Martin Fowler's TechnicalDebt" target="_blank">interesting topic</a> that <a href="http://blog.codinghorror.com/paying-down-your-technical-debt/" title="Paying Down Your Technical Debt" target="_blank">you should care about</a>). This day will happen when you&#8217;re spending more time in fixing issues than in adding new features to your software.</p>
<p>The problem continues if you try to reinventing the wheel or if you don&#8217;t realize that the plane is already invented. It&#8217;s 21st century, you can fly with the appropriate machine.</p>
<h4>The particular concern</h4>
<p>As I said at the beginning of this entry, he is a <a href="http://www.oracle.com/technetwork/java/javaee/overview/index.html" title="Java EE Overview" target="_blank">Java EE</a> developer that uses <a href="https://spring.io/" title="Spring" target="_blank">Spring Framework</a> in his daily work. But he still has to program for <a href="http://www-01.ibm.com/support/docview.wss?uid=swg21570083" title="End of Support for WebSphere Application Server 6.1" target="_blank">WebSphere Application Server 6.1</a> (a.k.a. WAS 6.1, that is <a href="http://en.wikipedia.org/wiki/Java_EE_version_history#J2EE_1.4_.28November_11.2C_2003.29" title="Wikipedia J2EE 1.4" target="_blank">Java EE 1.4</a> compliance using <a href="http://www.oracle.com/technetwork/java/eol-135779.html" title="Oracle Java SE Support Roadmap" target="_blank">Java 5 SE</a>) using <a href="http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/" title="Spring Framework 3.0 Reference Documentation" target="_blank">Spring framework 3</a> (<a href="https://spring.io/blog/2007/11/19/spring-framework-2-5-released" title="Spring Framework 2.5 released" target="_blank">2.5</a> for some projects)</p>
<p>At the time of this writing, <a href="http://www.oracle.com/us/corporate/press/1957557" title="Oracle Press Release Java EE 7" target="_blank">Java EE 7</a> is already released and the current version of <a href="http://projects.spring.io/spring-framework/" title="Spring Framework" target="_blank">Spring Framework is 4.0.6</a>. Not mentioning that Java 8<a href="http://www.oracle.com/us/corporate/press/2172618" title="Oracle Announces Java 8" target="_blank"></a> is now with us.</p>
<p>Thus, he wants to get up to date for improving the way he writes code that will be profitable for the company he works for.</p>
<p>I appreciate his request, because I&#8217;ll have to review what I really know.</p>
<p>Well. Enough introduction. In coming posts I will write about my particular thoughts of what you can do to know Java a little better.</p>
<p>Next, a summary of the topics that I want to talk about:</p>
<h4>Suggested topics</h4>
<ul>
<li><a href="http://www.oracle.com/technetwork/java/javase/overview/index.html" title="Java SE at a Glance" target="_blank">Java SE</a></li>
<p>The Java EE platform is built on top of the Java SE platform. The Java EE platform provides a particular API for server programming. So,it&#8217;s very reasonable to have a good knowledge of Java SE.</p>
<p>In particular, I assume that you have basic knowledge of Java.</p>
<p>But if you want to improve, you need to know the new features that have been published during the last years:</p>
<ul>
<li><a href="http://docs.oracle.com/javase/1.5.0/docs/relnotes/features.html#lang" title="New Features and Enhancements J2SE 5.0" target="_blank">Java 5</a></li>
<p><a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/generics.html" title="Generics" target="_blank">Generics</a>, <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html" title="The For-Each Loop" target="_blank">enhanced loops</a>, <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html" title="Autoboxing" target="_blank">autoboxing</a>, <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html" title="Enums" target="_blank">enums</a> (I love them), <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html" title="Varargs" target="_blank">varargs</a>, <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html" title="Static Import" target="_blank">static import</a>, and maybe the most important: <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html" title="Annotations" target="_blank">annotations</a> (they change our life as Java developers)</p>
<li><a href="http://www.oracle.com/technetwork/java/javase/features-141434.html" title="Highlights of Technology Changes in Java SE 6" target="_blank">Java 6</a></li>
<p><a href="http://www.onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html" title="JDBC 4.0 Enhancements in Java SE 6" target="_blank">JDBC 4.0</a>, Support for the Web Services stack and XML processing, and <a href="http://www.oracle.com/technetwork/articles/javase/beta2-135158.html" title="What's New in Java SE 6" target="_blank">many more</a>. </p>
<li><a href="http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html" title="Java SE 7 Features and Enhancements" target="_blank">Java 7</a></li>
<p>A quite <a href="http://radar.oreilly.com/2011/09/java7-features.html" title="A look at Java 7's new features" target="_blank">handy features for developing</a> like <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html" title="Strings in switch Statements" target="_blank">Strings in switch statements</a>, <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html" title="Binary Literals" target="_blank">Binary integral literals</a> and <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html" title="Underscores in Numeric Literals" target="_blank">underscores in numeric literals</a>, <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html" title="Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking" target="_blank">Multi-catch and more precise rethrow</a>, <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html" title="Type Inference for Generic Instance Creation" target="_blank">diamond operator</a>, <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html" title="The try-with-resources Statement" target="_blank">try-with-resources</a>, <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/non-reifiable-varargs.html" title="Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods" target="_blank">Simplified varargs method invocation</a>.</p>
</ul>
<p>As Java 8 has been released very recently, you can skip it for a little while.</p>
<li><a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/" title="Java Concurrency" target="_blank">Java Concurrency</a></li>
<p>Why a specific section for Java SE Concurrency?</p>
<p>Because in Java SE 5 everything changed. Concurrency in Java was improved in a way that provides a more natural approach to multi-threading (I had great joy with two of the enhancement of Java 5: <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/generics.html" title="Java Generics" target="_blank">Generics </a>and <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html" title="Java Callable" target="_blank">Callable</a>) and at the same time it avoids the long-term errors that the concurrency library had: the method <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#stop--" title="Java Thread stop" target="_blank">Thread.stop()</a> (actually, it already exists, and <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html" title="Why is Thread.stop deprecated?" target="_blank">I don&#8217;t know why</a>)</p>
<p>Not only you need to try not using Thread.start() anymore, try ExceutorService instead, you also need to know about Future and the new way to synchronize threads for understanding new features for concurrency of Java EE 7.</p>
<p>Besides, it&#8217;s really an improvement to know about <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html" title="Executors" target="_blank">Executor Framework</a> in Java.</p>
<p>There are a couple of good Java Concurrency tutorials:</p>
<ul>
<li><a href="http://www.vogella.com/tutorials/JavaConcurrency/article.html" title="Vogella's concurrency" target="_blank">Vogella&#8217;s Java concurrency (multi-threading) &#8211; Tutorial</a></li>
<li><a href="http://tutorials.jenkov.com/java-concurrency/index.html" title="Jenkov's Concurrency" target="_blank">Jenkov&#8217;s Java Concurrency / Multithreading Tutorial</a> and <a href="http://tutorials.jenkov.com/java-util-concurrent/index.html" title="Jenkov's concurrency utilities" target="_blank">Java Concurrency Utilities</a></li>
</ul>
<li><a href="http://www.oracle.com/technetwork/java/javaee/overview/index.html" title="Java EE at a Glance" target="_blank">Java EE 7</a></li>
<p>In spite of there are only a few <a href="http://www.oracle.com/technetwork/java/javaee/overview/compatibility-jsp-136984.html" title="Java EE Compatibility" target="_blank">Java EE 7 compatible servers</a>, it&#8217;s time to know about the <a href="http://www.infoworld.com/slideshow/105268/11-hot-improvements-java-ee-7-220465" title="11 hot improvements to Java EE 7" target="_blank">exciting new features</a> that will allow you to create better and faster applications:</p>
<ul>
<li>HTML5 (<a href="http://docs.oracle.com/javaee/7/tutorial/doc/websocket.htm#GKJIQ5" title="Java API for WebSocket" target="_blank">WebSockets</a> and <a href="http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB" title="JSON Processing" target="_blank">JSON</a>)</li>
<li><a href="http://docs.oracle.com/javaee/7/tutorial/doc/partmessaging.htm#GFIRP3" title="Messaging" target="_blank">Simplified JMS 2.0 API</a></li>
<li><a href="http://docs.oracle.com/javaee/7/tutorial/doc/batch-processing.htm#GKJIQ6" title="Batch Processing" target="_blank">Batch applications</a></li>
<li><a href="http://docs.oracle.com/javaee/7/tutorial/doc/concurrency-utilities.htm" title="Concurrency Utilities for Java EE" target="_blank">Concurrency utilities</a> (at last <a href="https://jcp.org/en/jsr/detail?id=236" title="JSR 236: Concurrency Utilities for Java EE" target="_blank">JSR 236</a> is finished)</li>
<li><a href="http://docs.oracle.com/javaee/7/tutorial/doc/partcdi.htm#GJBNR" title="Contexts and Dependency Injection for Java EE" target="_blank">Context Dependency Injection</a> (CDI. Yeah, introduced in Java EE 6, it has been enhanced to compete with Spring&#8217;s @Autowired)</li>
<li>Java API for RESTful Web Services (JAX-RS) 2.0 (<a href="http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs.htm#GIEPU" title="RESTful" target="_blank">webservices</a>, <a href="http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs-client.htm#BABEIGIH" title="Accesing REST" target="_blank">clients</a> and <a href="http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs-advanced.htm#GJJXE" title="JAX-RS: Advanced Topics and an Example" target="_blank">more</a>)</li>
<li><a href="http://docs.oracle.com/javaee/7/tutorial/doc/servlets.htm#BNAFD" title="Java Servlet TEchnology" target="_blank">Servlet 3.1</a></li>
</ul>
<li><a href="https://spring.io/projects" title="Spring projects" target="_blank">Spring Projects</a></li>
<p>I want to create particular blog entries for each Spring project that I&#8217;ve worked with, but in the meantime, the best way to getting started would be to take a look to the <a href="https://spring.io/guides" title="Spring guides" target="_blank">guides</a> that they provide.</p>
<li>Other technologies good to know</li>
<p>Since you&#8217;re using Java for writing programs to build solutions for business, it&#8217;s good to know the new environments that provides modern approaches for the current challenges.</p>
<p>You have to take a look to <a href="http://en.wikipedia.org/wiki/NoSQL" title="NoSQL from Wikipedia" target="_blank">NoSQL</a>, being <a href="http://www.mongodb.org/" title="mongoDB" target="_blank">MongoDB</a> the most popular, with good <a href="http://docs.mongodb.org/manual/" title="The MongoDB 2.6 Manual" target="_blank">documentation</a>, including <a href="http://docs.mongodb.org/ecosystem/drivers/java/" title="Java MongoDB Driver" target="_blank">programming with Java</a>.</p>
<p>The next step should be <a href="http://en.wikipedia.org/wiki/Big_data" title="Big data from Wikipedia" target="_blank">Big Data</a>. <a href="http://hadoop.apache.org/" title="Apache Hadoop" target="_blank">Hadoop</a> is the project that you have to pay attention for, but it&#8217;s so big, with several related projects, and so complex, that I still haven&#8217;t found a good introductory tutorial.</p>
<p>Finally, <a href="http://en.wikipedia.org/wiki/Asynchronous_I/O" title="Asynchronous I/O from Wikipedia" target="_blank">Asynchronous I/O</a>, that is the new solution for a problem that has been created by the new economy based on the internet of the things, that is, the need of handle scaling transactions from hundreds, thousands, even millions of users and the requirement of high-performance, high-speed for these operations.</p>
<p>There are several new frameworks that are worth it: <a href="http://akka.io/" title="Akka" target="_blank">Akka</a>, <a href="http://malsolo.com/blog4java/?p=35" title="Getting started with Vert.x" target="_blank">Vert.x</a>, <a href="https://github.com/reactor/reactor" title="Reactor" target="_blank">Reactor</a> (<a href="https://spring.io/blog/2013/05/13/reactor-a-foundation-for-asynchronous-applications-on-the-jvm" title="Reactor" target="_blank">a foundational framework</a> for <a href="https://spring.io/blog/2013/07/18/reactor-1-0-0-m1-a-foundation-for-asynchronous-fast-data-applications-on-the-jvm" title="Reactor 1.0.0.M1" target="_blank">asynchronous applications on the JVM</a>, <a href="https://spring.io/blog/2014/05/06/reactor-1-1-0-release-now-available" title="Reactor 1.1.0" target="_blank">by Spring</a>, but it&#8217;s not part of the portfolio) and <a href="http://nodejs.org/" title="Node.js" target="_blank">Node.js</a> (yes, it&#8217;s JavaScript)</p>
</ul>
<p>That&#8217;s all for now. I hope my colleague finds this entry interesting and I wish it is the first of a series of articles.</p>
<p>Let&#8217;s see.</p>
]]></content:encoded>
			<wfw:commentRss>http://malsolo.com/blog4java/?feed=rss2&#038;p=79</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
