//
you're reading...

Development

Part 1 : Web application development using AngularJS, Spring Boot and Maven – Setup

I have been using Spring Framework and Maven for my enterprise application development for long time now. I am a big fan of Spring Framework but a typical Maven and Spring based application requires a fair amount XML configuration to get started.

Along comes the new Spring initiative called Spring Boot that aims at accelerating application development. As per Spring Boot website, it takes an opinionated view of building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible. You can use it to create stand-alone Java applications that can be started using ‘java -jar’ or more traditional WAR deployments.Spring Boot offers many benefits

  • It provides opinionated ‘starter’ POMs to simplify your Maven configuration
    It configures resources based on what it finds in your classpath. By simply including the spring-boot-starter-data-jpa module as part of your pom.xml, Spring Boot’s auto-configuration engine will configure your application for database access, and will create the necessary beans within the Spring application context. To add MongoDB support in your application, simply include spring-boot-starter-data-mongodb in your pom.xml.
  • It also provides Opinionated dependencies
    Spring Boot includes needed dependencies automatically, for example, Logback and slf4j for logging, Jackson for handling JSON data, Servlet apis for web applications.
  • And it is Production ready
    Spring Boot also includes helpful features that you often need when you push an application into production. By including spring-boot-starter-actuator, Spring Boot automatically provides web endpoints that you can use to monitor application health, provide basic metrics or use to analyze production issues (such as thread deadlocks).

This post describes the steps I followed to get started with Maven and Spring Boot development.

Goal for this post

  • How to create a starter project using Maven archetype
  • How to include Spring Boot support in the project

Setup the project

  • Change to your working directory
  • Generate Maven project using quickstart Maven archetype
    mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart
    

    Enter details for your application

    Define value for property 'groupId': : com.rajandesai.proto
    Define value for property 'artifactId': : starter-app-ng
    Define value for property 'version':  1.0-SNAPSHOT: : 0.0.1-SNAPSHOT
    Define value for property 'package':  com.rajandesai.proto: : com.rajandesai.proto.springboot
    Confirm properties configuration:
    groupId: com.rajandesai.proto
    artifactId: starter-app-ng
    version: 0.0.1-SNAPSHOT
    package: com.rajandesai.proto.springboot
    

    At the end of it you should see the following structure

    starter-app-ng/
        ├── pom.xml
        └── src
            ├── main
            │    └── java
            │        └── com
            │            └── rajandesai
            │                └── proto
            │                    └── springboot
            │                        └── App.java
            └── test
                └── java
                    └── com
                        └── rajandesai
                            └── proto
                                └── springboot
                                    └── AppTest.java
    

    NOTE: Spring Boot allows you to create a project without having to define web.xml.

  • import eclipse project as existing maven project

    • Select File -> import
      • Select Maven -> Existing Maven Projects from the import dialog
        • Select base directory of the project created by maven in the previous step

    NOTE: You may have to select project and run Maven -> Update project to clear problems like resources out of date.

  • Setup Spring Boot

    • Modify pom.xml
      • Change packaging to war
        <packaging>war</packaging>
        
      • Add support for Spring Boot. By default Tomcat is enabled.
        <!-- Spring Boot Support -->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.0.0.RC4</version>
        </parent>       
        <!-- Spring Boot Repositories -->
        <repositories>
            <repository>
                <id>spring-snapshots</id>
                <url>http://repo.spring.io/libs-snapshot</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>spring-snapshots</id>
                <url>http://repo.spring.io/libs-snapshot</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </pluginRepository>
        </pluginRepositories>       
        <dependencies>
            <!-- Spring Boot -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>           
        </dependencies>
        
      • Remove <junit> dependency from this pom as spring-boot-starter-test includes the latest available junit by default.

      • Add <build> section

        • configure spring-boot-maven-plugin
          <build>
              <plugins>
                  <plugin>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-maven-plugin</artifactId>
                  </plugin>
              </plugins>  
          </build>
          
    • Create simple Hello page to test the setup
      NOTE: Spring Boot adds /static, /public, /resources, /META-INF/resources directories to serve static content (.html, .js, .css et al).

      • Add source folder src/main/resources/ to the eclipse project and create directory called static in the src/main/resources/ directory
        ├── pom.xml
        └── src
            ├── main
            │    ├── java
            │    │    └── com
            │    │        └── rajandesai
            │    │            └── proto
            │    │                └── springboot
            │    │                    └── App.java
            │    └── resources
            │           └── static
            │                   └── index.html
            └── test
                └── java
                     └── com
                          └── rajandesai
                                └── proto
                                    └── springboot
                                        └── AppTest.java
        
      • Create <project_root_dir>/src/main/resources/static/index.html
        			<html>
            			<head>
                			<title>Starter App</title>
            			</head>
            			<body>
                			<h2>Hello World!!!</h2>
            			</body>
        			</html>
        			

    • Make Spring Boot application executable

      • Fastest way to test Spring Boot application is by creating an executable application. Spring Boot can package everything in a single, executable JAR/WAR that uses the main() method to configure and run the application OR can use embedded server (Tomcat by default) to deploy the application in an HTTP runtime environment. The following example shows both approaches.
        • Modify the class com.rajandesai.proto.springboot.App.java
        			package com.rajandesai.proto.springboot;
        			import org.springframework.boot.SpringApplication;
        			import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
        			import org.springframework.boot.builder.SpringApplicationBuilder;
        	  		import org.springframework.boot.context.web.SpringBootServletInitializer;
        			import org.springframework.context.annotation.Configuration;
        
        			@Configuration
        			@EnableAutoConfiguration
        			public class App extends SpringBootServletInitializer {
        				public static void main(String[] args) throws Exception {
        					ApplicationContext ctx = SpringApplication.run(App.class, args);
        				}
        				@Override
        			  	protected SpringApplicationBuilder configure(
        			 	  	SpringApplicationBuilder application) {
        				  	return application.sources(App.class);
        			  	}
        			}		
        			
        • @Configuration annotation marks the class as a source of @bean definations used to configure the Spring application context
        • @EnableAutoConfiguration annotation enables auto configuration option that tells Spring Boot to configure beans based on classpath, other bean definations, and properties
        • @ComponentScan annotation is used to enable Spring Boot to scan Controllers other Services in the current project.
        • main method is defined so that we can run this application using java -jar option. This method uses SpringApplication.run to execute the application. As shown above, the run method returns the ApplicationContext for this application.
        • To execute this application in an embedded server (Tomcat by default), we need to initialize the servlet and launch the application. This is done by extending SpringBootServletInitializer and overriding the configure() method.
          • This is a pure java class used to configure web.xml for your application
          • configure() method provides a way to register classes needed to execute your application.
    • Configure logger (by default commons-logging and logback is configured).
      • Add src/main/resources/logback.xml
        <?xml version="1.0" encoding="UTF-8"?>
        <configuration>
            <include resource="org/springframework/boot/logging/logback/base.xml"/>
            <logger name="org.springframework.web" level="DEBUG"/>
            <logger name="com.rajandesai" level="DEBUG"/>
        </configuration>        
        
      • To configure log4j, take a look at this link

    • Test initial setup

      • deploy application to the embedded Tomcat server:
        mvn spring-boot:run
        
      • Point your browser to
            http://localhost:8080/
        

        or in the terminal window type

            curl http://localhost:8080 
        
      • If you see/get the index.html created above, you have successfully created and deployed your first web application using Spring Boots.

Production ready – Support for Monitoring and Application Management

For more information take a look at this reference guide

Sum it up

You have a fully functional web application that uses Spring Boot framework. The application doesn’t do much yet but I plan to use this as the starting point for my AngularJS based application.

Discussion

No comments yet.

Post a Comment


*

Categories