Tuesday, 10 July 2018

Execute spring project using maven

In this post, you are going to learn
a.   How to create simple maven java project
b.   Add dependencies in pom.xml
c.   Write Hello World spring boot application.
d.   Run the spring boot application using maven

Step 1: How to create simple maven java project?
Maven provides number of archetypes to create project skeltons.

For example,
maven-archetype-quickstart : Generate simple maven project.
maven-archetype-j2ee-simple : Generate simple j2ee application.

Open command prompt and execute the command "mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart"

When you execute above command, maven asks groupId, artifactId, version, and package information and create a simple project.

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
Define value for property 'groupId': org.selflearningjava
Define value for property 'artifactId': HelloWorld
Define value for property 'version' 1.0-SNAPSHOT: : 1
Define value for property 'package' org.selflearningjava: : com.sample.app
Confirm properties configuration:
groupId: org.selflearningjava
artifactId: HelloWorld
version: 1
package: com.sample.app
 Y: : Y
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\Users\krishna\Documents\Study\Spring Boot\examples\projects
[INFO] Parameter: package, Value: com.sample.app
[INFO] Parameter: groupId, Value: org.selflearningjava
[INFO] Parameter: artifactId, Value: HelloWorld
[INFO] Parameter: packageName, Value: com.sample.app
[INFO] Parameter: version, Value: 1
[INFO] project created from Old (1.x) Archetype in dir: C:\Users\krishna\Documents\Study\Spring Boot\examples\projects\HelloWorld
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:51 min
[INFO] Finished at: 2018-04-20T14:44:35+05:30
[INFO] ------------------------------------------------------------------------

Project structure looks like below.




package com.sample.app;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

Step 2:  Add dependencies in pom.xml
Pom.xml file will be located under the project directory. Add below maven dependencies to pom.xml.

         <parent>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-parent</artifactId>
                  <version>2.0.1.RELEASE</version>
         </parent>

         <dependencies>

                  <dependency>
                           <groupId>org.springframework.boot</groupId>
                           <artifactId>spring-boot-starter-web</artifactId>
                  </dependency>

         </dependencies>

Final pom file looks like below.

pom.xml
<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>org.selflearningjava</groupId>
  <artifactId>HelloWorld</artifactId>
  <packaging>jar</packaging>
  <version>1</version>
  <name>HelloWorld</name>
  <url>http://maven.apache.org</url>
  
  <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.0.1.RELEASE</version>
  </parent>
 
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
 
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
  </dependencies>
  
</project>

Step 3: Write Hello World spring boot application

Update App.java like below.


App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class App 
{
 @RequestMapping("/")
 @ResponseBody
 String home() {
  return "Hello World!";
 }

 public static void main(String[] args) throws Exception {
  SpringApplication.run(App.class, args);
 }
}

Step 4: Run the spring boot application using maven
Go to the directory, where pom.xml file is located and execute the command ‘mvn spring-boot:run’.


You can able to see that, maven start the tomcat server and deploy the application.

[INFO] --- spring-boot-maven-plugin:2.0.1.RELEASE:run (default-cli) @ HelloWorld ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)
 ..........
 ..........
 ..........
2018-04-20 14:55:54.251  INFO 11412 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-04-20 14:55:54.262  INFO 11412 --- [           main] com.sample.app.App                       : Started App in 3.772 seconds (JVM running for 9.045)

Once the application started, open the url ‘http://localhost:8080/’ in browser, you can able to see ‘Hello World’ message


Previous                                                 Next                                                 Home

Monday, 9 July 2018

Spring CLI: Hello World example

Create HelloWorld.groovy file with below content.

HelloWorld.groovy
@RestController
class HelloWorld {

 @RequestMapping("/")
 String home() {
  "Hello World!"
 }

}

Execute the command ‘spring run HelloWorld.groovy’.

It starts the embedded tomcat server and deploy HelloWorld application.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)

2018-04-20 13:27:36.397  INFO 17248 --- [       runner-0] o.s.boot.SpringApplication               : Starting application on INLN50911363A with PID 17248 (started by krishna in C:\Users\krishna\Documents\Study\Spring Boot\examples)
2018-04-20 13:27:36.409  INFO 17248 --- [       runner-0] o.s.boot.SpringApplication               : No active profile set, falling back to default profiles: default
2018-04-20 13:27:36.694  INFO 17248 --- [       runner-0] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@8382c0f: startup date [Fri Apr 20 13:27:36 IST 2018]; root of context hierarchy
2018-04-20 13:27:38.779  INFO 17248 --- [       runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-04-20 13:27:38.816  INFO 17248 --- [       runner-0] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-04-20 13:27:38.817  INFO 17248 --- [       runner-0] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-04-20 13:27:38.908  INFO 17248 --- [ost-startStop-1] org.apache.catalina.loader.WebappLoader  : Unknown loader org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader@3ab33fdd class org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader
2018-04-20 13:27:38.974  INFO 17248 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-04-20 13:27:38.974  INFO 17248 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2284 ms
2018-04-20 13:27:39.219  INFO 17248 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-04-20 13:27:39.228  INFO 17248 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-04-20 13:27:39.229  INFO 17248 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-04-20 13:27:39.231  INFO 17248 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-04-20 13:27:39.232  INFO 17248 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-04-20 13:27:39.450  INFO 17248 --- [       runner-0] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-20 13:27:39.822  INFO 17248 --- [       runner-0] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@8382c0f: startup date [Fri Apr 20 13:27:36 IST 2018]; root of context hierarchy
2018-04-20 13:27:39.931  INFO 17248 --- [       runner-0] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String HelloWorld.home()
2018-04-20 13:27:39.940  INFO 17248 --- [       runner-0] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-04-20 13:27:39.943  INFO 17248 --- [       runner-0] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-04-20 13:27:39.999  INFO 17248 --- [       runner-0] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-20 13:27:40.002  INFO 17248 --- [       runner-0] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-20 13:27:40.531  INFO 17248 --- [       runner-0] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-04-20 13:27:40.601  INFO 17248 --- [       runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-04-20 13:27:40.609  INFO 17248 --- [       runner-0] o.s.boot.SpringApplication               : Started application in 5.284 seconds (JVM running for 8.153)

Open browser hit the url  ‘http://localhost:8080/’ in browser, you can able to see ‘Hello World!’ message.




Previous                                                 Next                                                 Home

Working with Spring Boot CLI

Spring Boot CLI is a command line interface tool, by using this you can quickly create spring projects.

In this post, I am going to show you the setup and basics of spring boot CLI.

Setting up Spring Boot CLI
Download spring boot from below location. Depends on the spring boot version that you are using, url can change.

Extract the downloaded zip file, you can able to see below kind of structure.




You can go through the instructions in ‘INSTALL.txt’ file.

Spring cli executable is located at bin directory. We should add the path of spring bin directory to system path.

How to add spring cli bin path to system path? 
On Windows systems, follow below procedure. 
Step1: Right click computer icon, and open the properties window.


Step 2: Click on the Advanced system settings tab as shown below. Then it will open the system properties window.


Step3: Open the System properties and choose the Advanced tab. Click on the “Environment Variable” button.


Step 4
You will get a window like below. It contains 2 sections, one for user variables and other for System variables section.


Edit the path from system variables section, and add the spring bin path.

On Linux Systems
If spring cli is extracted to the location "/usr/krishna/spring-2.0.1.RELEASE/bin"

You have to update the path like below
export PATH=/usr/krishna/spring-2.0.1.RELEASE/bin:$PATH
                          OR
you can update the path variable in /etc/environment file for linux or .profile file in AIX like below
export PATH=/usr/krishna/spring-2.0.1.RELEASE/bin:$PATH

Testing the spring cli setup
Open command prompt (or) shell and execute the command ‘spring’.
C:\>spring
usage: spring [--help] [--version]
       <command> [<args>]

Available commands are:

  run [options] <files> [--] [args]
    Run a spring groovy script

  grab
    Download a spring groovy script's dependencies to ./repository

  jar [options] <jar-name> <files>
    Create a self-contained executable jar file from a Spring Groovy script

  war [options] <war-name> <files>
    Create a self-contained executable war file from a Spring Groovy script

  install [options] <coordinates>
    Install dependencies to the lib/ext directory

  uninstall [options] <coordinates>
    Uninstall dependencies from the lib/ext directory

  init [options] [location]
    Initialize a new project using Spring Initializr (start.spring.io)

  encodepassword [options] <password to encode>
    Encode a password for use with Spring Security

  shell
    Start a nested shell

Common options:

  -d, --debug Verbose mode
    Print additional status information for the command you are running


See 'spring help <command>' for more information on a specific command.

If you able to see above kind of output, then spring cli installation is successful.





Previous                                                 Next                                                 Home

Sunday, 8 July 2018

Spring boot: Hello World Application

Below step-by-step procedure explains how to develop and run simple application using spring boot.

Requirements: Eclipse

Step 1: Open Eclipse, and create new maven project.


Select the check box 'Create a simple project (skip archetype selection)'



Click on Next button.





Give the Group Id as 'org.selflearning', artifact id as 'springDemo' and version as 1.

Click on Finish button.

Project is created like below.


Step 2:  Add the spring boot dependencies to pom.xml.


<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Total pom looks like below.

pom.xml
<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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.selflearning</groupId>
 <artifactId>springDemo</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.1.RELEASE</version>
 </parent>

 <dependencies>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

 </dependencies>

</project>

Step 3: Create a package 'com.sample.demo' and define the class HomePageController like below.


HomePageController.java
package com.sample.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class HomePageController {
 @RequestMapping("/")
 @ResponseBody
 String home() {
  return "Hello World!";
 }

 public static void main(String[] args) throws Exception {
  SpringApplication.run(HomePageController.class, args);
 }
}


Run above application and hit the url ‘http://localhost:8080/’ in browser, you can able to see ‘Hello World!’ message.

SpringApplication.run(HomePageController.class, args);
Run the SpringApplication from the specified source using default settings.

@Controller
If you annotate any class with this annotation, then Spring considers it when handling incoming web requests.

@RequestMapping
It maps the url to specific function.

@EnableAutoConfiguration
This annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added.



Previous                                                 Next                                                 Home

Introduction to Spring Boot

By using spring boot, you can create standalone spring applications. Any typical web application requires Servlet container, caching library, messaging service etc., By using spring boot, you can get rid of this, spring boot provides all these capabilities by default.

Most of the spring boot applications require very minimal spring configuration.

Below are the features of spring boot.

1.   Create stand-alone Spring applications
2.   Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
3.   Provide opinionated 'starter' POMs to simplify your Maven configuration
4.   Automatically configure Spring whenever possible
5.   Provide production-ready features such as metrics, health checks and externalized configuration
6.   Absolutelyno requirement for XML configuration

System Requirements
At the time of writing this tutorial, 'Spring Boot 2.0.1.RELEASE' is the latest. It requires
1.   java 8 or higher,
2.   Spring Framework 5.0.5.RELEASE or above.

Is spring boot support maven and gradle?
Yes, explicit build support is provided for Maven 3.2+ and Gradle 4.

What are the servlet containers supported by spring boot?
You can deploy a spring boot application in any Servlet 3.1+ compatible containers.

Spring boot supports below embedded servlet containers officially.
Servlet Container
Servlet Version
Tomcat 8.5
3.1
Jetty 9.4
3.1
Undertow 1.4
3.1

If you would like to know more about embedded servlet container, I will recommend you go through my below tutorial series.

Reference

Previous                                                 Next                                                 Home

spring boot core tutorial

Introduction to Spring Boot
Spring boot: Hello World Application
Working with Spring Boot CLI
Spring CLI: Hello World example
Execute spring project using maven
Spring boot: Create an executable jar using maven
Spring Boot: ComponentScan
Is SpringBootApplication annotation trigger component scan?
Spring boot: How to define main application class?
Spring boot: Configuration annotation example
Programmatically shut down Spring Boot application
Spring boot: Importing Additional Configuration Classes
Spring boot: Importing xml configuration
Spring boot: Run the application in debug mode
Spring boot: @Autowired annotation example
Spring boot: Autowire spring bean by name
Spring boot: @SpringBootApplication annotation
Spring boot: Customizing the banner
Spring boot: Generate banner programmatically
SpringBoot: Specify banner mode (disable, log, console)
SpringApplicationBuilder tutorial
Spring boot: Application Events and Listeners
Spring Boot: Access Spring application arguments
Spring boot: CommandLinePropertySource tutorial
Spring boot: inject application arguments using @Value annotation
Spring boot: CommandLineRunner : Run the code only once
Spring boot: ApplicationRunner: Run the code only once
Spring boot: Ordering the execution of Application Runner (or) Command line runner
Spring boot: Registering shutdown hook with the JVM
Spring boot: Listening to exit code events
Spring boot: ExitCodeGenerator and Exceptons
Spring boot: mapping exit codes and exceptions
Spring boot: Get the port of spring boot application
Spring boot: RandomValuePropertySource: Working with random values
Spring boot: Application property files
Spring boot: place holders in properties file
Spring yaml configuration
Spring boot: configure yaml properties using prefix
Spring Boot: @ConfigurationProperties tutorial
Spring boot: @ConfigurationProperties: map properties by prefix
Spring boot: @EnableConfigurationProperties example
Spring boot: Configure bean from application environment properties
Spring boot: Relaxed Binding
Spring boot: Properties Conversion
Spring Boot: Validating properties
Spring boot: Profiles
Spring boot: How to get all active profiles
Spring boot: Activate profiles programmatically
Profile specific properties
@Value: Populate list from a property
Get reference of ApplicationContext

Saturday, 7 July 2018

Junit: Theories: @TestedOn annotation

If you annotate any @Theory method using @TestedOn annotation, then the int parameter with @TestedOn causes it to be supplied with values from the ints array.

Let me explain with an example.




In the above example, I passed [2, 4] as an argument to a, and [1, 3] as an argument to b.

Junit run the test cases with every combination of arguments a and b.

For example, it runs the test case with below combinations.
a : 2, b : 1
a : 2, b : 3
a : 4, b : 1
a : 4, b : 3



Find the below working example.

TestApp.java

package com.sample.test;

import static org.junit.Assert.assertEquals;

import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.experimental.theories.suppliers.TestedOn;
import org.junit.runner.RunWith;

@RunWith(Theories.class)
public class TestApp {

 @Theory
 public void strReverseTwice(@TestedOn(ints = { 2, 4 }) int a, @TestedOn(ints = { 1, 3 }) int b) {
  //System.out.println("a : " + a + ", b : " + b);
  assertEquals(a + b, b + a);
 }

}


Previous                                                 Next                                                 Home