Creating an application in Spring

Before we create an application in Spring, first we need to obtain Spring Library. We can download the Spring distribution ZIP files that are available in the Spring Maven Repository. Else, we can simply add the dependencies for Spring into project's pom.xml file whenever we use Maven for application development.

Spring packaging is modular, allowing you to pick and choose the component you want to use in your application. Spring comes with a large selection of sample applications that can be referred while building your application.

Obtaining Spring JAR files

  • Downloading Spring distribution ZIP files: The complete Spring Framework library can be downloaded by opening the link http://repo.spring.io/release/org/springframework/spring/ and selecting the appropriate subfolder for the version needed for your application development. Distribution ZIP files end with dist.zip, for example, spring-framework-4.1.4.RELEASE-dist.zip.

    Note

    While writing this book, the latest version was Spring Framework 4.1.4.

    Download the package and extract it. Under the lib folder, you will find a list of Spring JAR files that represents each Spring module.

  • Checking Spring out of GitHub: You can check out the latest version of code from Spring's GitHub repository at https://github.com/spring-projects/spring-framework.

    To check out the latest version of the Spring code, first install Git from http://git-scm.com/, open the Git Bash tool, and run the following command:

    git clone https://github.com/spring-projects/spring-framework
    

Understanding Spring packaging

After extracting the downloaded Spring Framework ZIP file, you will get the directory structure, as shown in the following screenshot:

Understanding Spring packaging

The spring-framework-4.14.RELEASE folder, as shown in the preceding screenshot, contains docs, libs, and schema subfolders. The lib folder contains the Spring JAR files, as shown in the following screenshot:

Understanding Spring packaging

Shown in the preceding screenshot is a list of JAR files required while developing applications using Spring. You can find more details on these JAR files at http://www.learnr.pro/content/53560-pro-spring/40 and http://agile-hero.iteye.com/blog/1684338.

SpringSource Tool Suite

SpringSource Tool Suite (STS) is a powerful Eclipse-based development environment for developing Spring application. The latest version of STS can be downloaded from http://spring.io/tools/sts. We will use STS IDE for all our examples in this book. The following screenshot shows a snapshot of an STS dashboard:

SpringSource Tool Suite

Let's now create a simple Spring application using Spring STS.

The Spring application

With basic understanding of the Spring Framework, we can now create a simple Spring application example. All the examples in this book have been written using the STS IDE.

We will write a simple Spring application that will print greeting message to user. Do not worry if you do not fully understand all the code in this section; we'll go into much more detail on all the topics as we proceed through this book.

Creating a Spring project

The following steps will help you create your Spring project in STS:

  1. The first step in creating a Spring application is to create a new Spring project in the STS IDE. Navigate to File | New | Spring Project, as shown in the following screenshot:
    Creating a Spring project
  2. Name your Spring project SimpleSpringProject and select the Simple Java template, which creates a Simple Spring project using the Java build without a top-level package and with default Spring configuration and project natures, as shown in the following screenshot:
    Creating a Spring project
  3. Then, click on Finish, which will create the project in a workspace.

Adding required libraries

Let's add the basic Spring JAR files to the build path of this Spring project:

  1. Add the Spring Framework libraries and common logging API libraries to your project. The common login library can be downloaded from http://commons.apache.org/proper/commons-logging/download_logging.cgi. To add required libraries, right-click on the project named SimpleSpringProject and then click on the available options in the context menu, that is, Build Path | Configure Build Path to display the Java Build Path window, as shown in the following screenshot:
    Adding required libraries
  2. Now, use the Add External JARs button from the Libraries tab in order to include the following core JARs from the Spring Framework and common logging installation directories:
    • spring-aop-4.1.4.RELEASE
    • spring-aspects-4.1.4.RELEASE
    • spring-beans-4.1.4.RELEASE
    • spring-context-4.1.4.RELEASE
    • spring-context-support-4.1.4.RELEASE
    • spring-core-4.1.4.RELEASE
    • spring-expression-4.1.4.RELEASE
    • commons-logging-1.2

    The Libraries tab is as shown in the following screenshot:

    Adding required libraries

Now, you will have the content in your Project Explorer, as shown in the following screenshot:

Adding required libraries

Creating source files

Now let's create the actual source files under the SimpleSpringProject project:

  1. First, create the packages named org.springframework.chapter1.service and org.springframework.chapter1.main, as shown in the following screenshot. To do this, right-click on src in package explorer section and navigate to New | Package.
    Creating source files
  2. Create a class called MainClass.java inside the org.springframework.chapter1.main package. Then, create an interface named GreetingMessageService.java and its implementation class GreetingMessageServiceImpl.java inside the package org.springframework.chapter1.service, as shown in the following screenshot:
    Creating source files

The following is the content of interface GreetingMessageService.java and its implementation GreetingMessageServiceImpl.java:

  • GreetingMessageService.java:
    package org.springframework.chapter1.service;
    
    public interface GreetingMessageService {
       public String greetUser();
    }
  • GreetingMessageServiceImpl.java:
    package org.springframework.chapter1.service;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class GreetingMessageServiceImpl implements GreetingMessageService {
    
       public String greetUser() {
             return "Welcome to Chapter-1 of book Learning Spring Application Development";
       }
    
    }

The GreetingMessageService interface has a greetUser() method. The GreetingMessageServiceImpl class implements the GreetingMessageService interface and provides definition to the greetuser() method. This class is annotated with the @Service annotation, which will define this class as service class.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The following is the content of the file MainClass.java:

package org.springframework.chapter1.main;

import org.springframework.chapter1.service.GreetingMessageService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {
   public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext(
                       "beans.xml");
          GreetingMessageService greetingMessageService = context.getBean(
                       "greetingMessageServiceImpl", GreetingMessageService.class);
          System.out.println(greetingMessageService.greetuser());
   }
}

In MainClass.java, we are creating ApplicationContext using framework API, as shown in the following:

ApplicationContext context = new ClassPathXmlApplicationContext(
                      "beans.xml");

This API loads Spring beans configuration file named beans.xml, which takes care of creating and initializing all the bean objects. We use the getBean() method of the created ApplicationContext to retrieve required Spring bean from the application context, as shown in the following:

GreetingMessageService greetingMessageService = context.getBean(
   "greetingMessageServiceImpl", GreetingMessageService.class);

The getBean() method uses bean ID and bean class to return a bean object.

Creating the Spring bean configuration file

The Spring bean configuration file is used to configure the Spring beans in the Spring IoC container. As we have annotated the GreetingMessageServiceImpl class with @Service annotation, the next step is to add <context:component-scan> in the bean configuration file. To do this, follow these steps:

  1. Create a Spring Bean Configuration file under the src directory. To do this, right-click on src in package explorer section and then navigate to New | Spring Bean Configuration File.
  2. Enter the bean name beans and click on Next, as shown in the following screenshot:
    Creating the Spring bean configuration file
  3. Select the context option and click on Finish, as shown in the following screenshot:
    Creating the Spring bean configuration file
  4. Now the Spring bean configuration file is created. Add the following code to create an entry. The contents of the beans.xml file are as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    
       <context:component-scan base-package="org.springframework.chapter1.service"/>
    
    </beans>

When the Spring application gets loaded into the memory, in order to create all the beans, the framework uses the preceding configuration file, as shown in the following screenshot:

Creating the Spring bean configuration file

The Spring bean configuration file can be named anything, but developers usually keep the name beans.xml. This Spring bean configuration file should be available in classpath.

Tip

The S in the upper-right corner of the project icon indicates it is a Spring Project.

Running the program

Once you are done with creating source files and beans configuration files, you are ready for the next step, that is, compiling and running your program.

To execute the example, run the MainClass.java file. Right-click on MainClass.java and navigate to Run As | Java Application. If everything goes fine, then it will print the following message in STS IDE's console, as shown in the following screenshot:

Running the program

We have successfully created our first Spring application, where you learned how to create the Spring project and executed it successfully. We will see detailed examples in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.18.106.236