Spring 4 core example

In this post I will take you through Spring 4 version core example. You will see a different way to configure the application using @Configuration annotation.

  • Prerequisites:
    • Spring 4.0.6.RELEASE
    • Maven 3
    • JDK 1.8
    • IntelliJ IDEA
  • Create maven project from template:

$ mvn archetype:generate -DgroupId=com.naveenlabs.core -DartifactId=Spring-4-core-example -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

  • Update pom.xml file with Spring dependencies,
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.naveenlabs.core</groupId>
  <artifactId>Spring-4-core-example</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Spring-4-core-example</name>
  <url>http://maven.apache.org</url>
    <properties>
        <springframework.version>4.0.6.RELEASE</springframework.version>
    </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${springframework.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${springframework.version}</version>
      </dependency>
  </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

and run the command,

$ mvn clean install

or

$ mvn dependency:resolve

to update the dependency libraries for the project.

  • Add a SpringDemoBean.java in the same package as App.java. You are free to do it in any other package, but for the tutorials sake, we will keep it simple.

SpringDemoBean.java

package com.naveenlabs.core;

/**
 * Created by naveen.
 */
public class SpringDemoBean {

    public void greet(String message){
        System.out.println(message);
    }
}
  • Now, add a configuration class in the same package as App.java. You are free to do it in any other package, but for the tutorials sake, we will keep it simple.

SpringDemoConfig.java

package com.naveenlabs.core;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;

/**
 * Created by naveen.
 */
@Configuration
public class SpringDemoConfig {

    @Bean(name="springDemoBean")
    @Description("This is a simple bean example.")
    public SpringDemoBean springGreet(){
        return new SpringDemoBean();
    }
}

So far in our previous tutorials we have used XML to configure our bean context configuration definitions, but you could also do the same using annotations. All you need to tell Spring about a class being context configuration is to annotate it with @Configuration. Then we add @Bean annotation and give it a name, it is similar to giving id in xml configuration. We will add some description, which is completely optional but gives good readability and part of good practices. The description is added using @Description annotation too. Then we add a public method springGreet and return the instance of SpringDemoBean class. In real world applications you might want to change the return signature of method to some interface which SpringDemoBean will be implementing. And, that is it, we have a simple context configuration class.

  • Now, come to App.java and update it,
package com.naveenlabs.core;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
//        pass the config class parameter to fetch the context
        AbstractApplicationContext abstractApplicationContext = new AnnotationConfigApplicationContext(SpringDemoConfig.class);
//        get the bean by name
        SpringDemoBean springDemoBean = (SpringDemoBean) abstractApplicationContext.getBean("springDemoBean");
//        now pass a string of message attribute to greet method
        springDemoBean.greet("Greetings from Spring 4!!!! :)");
// its good to close context after the usage is finished.
        abstractApplicationContext.close();
    }
}

The comments in App.java should be sufficient to give you a better idea in what is happening, so I will skip it 🙂

  • Build the project and run it,

$ mvn clean install

java -cp target/Spring-4-core-example-1.0-SNAPSHOT.jar com.naveenlabs.core.App

Greetings from Spring 4!!!! 🙂