Codinko- Java Coding Tutorials

Category: Uncategorized (page 1 of 4)

sample spring boot application.yml ( alternative to application.properties)

spring:

  datasource:

    url: jdbc:mysql://${MYSQL_HOST}:3306/${MYSQL_DATABASE}

    username: ${MYSQL_USER}

    password: ${MYSQL_PASSWORD}

  jpa:

    hibernate:

      ddl-auto: update

    show-sql: true

server:

  port: 8081

Spring RestController annotation

  • A class annotated with the @Controller annotation has handler methods which return a view. 
  • However, if we use @ResponseBody annotation along with @Controller annotation, it will return the data directly in a serialized format.
  • Starting from Spring 4 and above, we can use @RestController annotation which is equivalent to using @Controller and @ResposeBody annotation.

 

Spring Boot- Getting Started

Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can run.

Most Spring Boot applications need very little Spring configuration.

  • You can use Spring Boot to create Java applications that can be started by using
     java -jar or more traditional war deployments.
  • There is also a  command line tool that runs “spring scripts”.

The primary goals around which Spring Boot is offered are:

  • Provide a radically faster and widely accessible getting-started experience for all Spring development.
  • Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
  • Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).
  • Absolutely no code generation and no requirement for XML configuration.

Servlet Containers

Spring Boot supports the following embedded servlet containers:

Name Servlet Version

Tomcat 9.0

4.0

Jetty 9.4

3.1

Undertow 2.0

4.0

You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container.

Installing Spring Boot

Spring Boot can be used with “classic” Java development tools or installed as a command line tool. Either way, you need Java SDK v1.8 or higher. Before you begin, you should check your current Java installation by using the following command:

$ java -version

If you are new to Java development or if you want to experiment with Spring Boot, you might want to try the Spring Boot CLI (Command Line Interface) first.

 

Installation Instructions for the Java Developer

You can use Spring Boot in the same way as any standard Java library. To do so, include the appropriate spring-boot-*.jar files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor. Also, there is nothing special about a Spring Boot application, so you can run and debug a Spring Boot application as you would any other Java program.

Although you could copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).

3.1.1. Maven Installation

Spring Boot is compatible with Apache Maven 3.3 or above. If you do not already have Maven installed, you can follow the instructions at maven.apache.org.

On many operating systems, Maven can be installed with a package manager. If you use OSX Homebrew, try brew install maven. Ubuntu users can run sudo apt-get install maven. Windows users with Chocolatey can run choco install maven from an elevated (administrator) prompt.

Spring Boot dependencies use the org.springframework.boot groupId. Typically, your Maven POM file inherits from the spring-boot-starter-parent project and declares dependencies to one or more “Starters”. Spring Boot also provides an optional Maven plugin to create executable jars.

The following listing shows a typical pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <!-- Override inherited settings -->
    <description/>
    <developers>
        <developer/>
    </developers>
    <licenses>
        <license/>
    </licenses>
    <scm>
        <url/>
    </scm>
    <url/>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

The spring-boot-starter-parent is a great way to use Spring Boot, but it might not be suitable all of the time. Sometimes you may need to inherit from a different parent POM, or you might not like our default settings. In those cases, see using-spring-boot.html for an alternative solution that uses an import scope.

Installing the Spring Boot CLI

The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to quickly prototype with Spring. It lets you run Groovy scripts, which means that you have a familiar Java-like syntax without so much boilerplate code.

You do not need to use the CLI to work with Spring Boot, but it is definitely the quickest way to get a Spring application off the ground.

Manual Installation

You can download the Spring CLI distribution from the Spring software repository:

Cutting edge snapshot distributions are also available.

Once downloaded, follow the INSTALL.txt instructions from the unpacked archive. In summary, there is a spring script (spring.bat for Windows) in a bin/ directory in the .zip file. Alternatively, you can use java -jar with the .jar file (the script helps you to be sure that the classpath is set correctly).

 

Quick-start Spring CLI Example

You can use the following web application to test your installation. To start, create a file called app.groovy, as follows:

@RestController
class ThisWillActuallyRun {

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

}

Then run it from a shell, as follows:

$ spring run app.groovy
The first run of your application is slow, as dependencies are downloaded. Subsequent runs are much quicker.

Open localhost:8080 in your favorite web browser. You should see the following output:

Hello World!

Developing Your First Spring Boot Application

This section describes how to develop a simple “Hello World!” web application that highlights some of Spring Boot’s key features. We use Maven to build this project, since most IDEs support it.

Before we begin, open a terminal and run the following commands to ensure that you have valid versions of Java and Maven installed:

$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
$ mvn -v
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Oracle Corporation
This sample needs to be created in its own folder. Subsequent instructions assume that you have created a suitable folder and that it is your current directory.

4.1. Creating the POM

We need to start by creating a Maven pom.xml file. The pom.xml is the recipe that is used to build your project. Open your favorite text editor and add the following:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

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

    <description/>
    <developers>
        <developer/>
    </developers>
    <licenses>
        <license/>
    </licenses>
    <scm>
        <url/>
    </scm>
    <url/>

    <!-- Additional lines to be added here... -->

</project>

The preceding listing should give you a working build. You can test it by running mvn package (for now, you can ignore the “jar will be empty – no content was marked for inclusion!” warning).

At this point, you could import the project into an IDE (most modern Java IDEs include built-in support for Maven). For simplicity, we continue to use a plain text editor for this example.

4.2. Adding Classpath Dependencies

Spring Boot provides a number of “Starters” that let you add jars to your classpath. Our applications for smoke tests use the spring-boot-starter-parent in the parent section of the POM. The spring-boot-starter-parent is a special starter that provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for “blessed” dependencies.

Other “Starters” provide dependencies that you are likely to need when developing a specific type of application. Since we are developing a web application, we add a spring-boot-starter-web dependency. Before that, we can look at what we currently have by running the following command:

$ mvn dependency:tree

[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT

The mvn dependency:tree command prints a tree representation of your project dependencies. You can see that spring-boot-starter-parent provides no dependencies by itself. To add the necessary dependencies, edit your pom.xml and add the spring-boot-starter-web dependency immediately below the parent section:

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

If you run mvn dependency:tree again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself.

4.3. Writing the Code

To finish our application, we need to create a single Java file. By default, Maven compiles sources from src/main/java, so you need to create that folder structure and then add a file named src/main/java/Example.java to contain the following code:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

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

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

}

Although there is not much code here, quite a lot is going on. We step through the important parts in the next few sections.

4.3.1. The @RestController and @RequestMapping Annotations

The first annotation on our Example class is @RestController. This is known as a stereotype annotation. It provides hints for people reading the code and for Spring that the class plays a specific role. In this case, our class is a web @Controller, so Spring considers it when handling incoming web requests.

The @RequestMapping annotation provides “routing” information. It tells Spring that any HTTP request with the / path should be mapped to the home method. The @RestController annotation tells Spring to render the resulting string directly back to the caller.

The @RestController and @RequestMapping annotations are Spring MVC annotations (they are not specific to Spring Boot). See the MVC section in the Spring Reference Documentation for more details.

4.3.2. The @EnableAutoConfiguration Annotation

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.

Starters and Auto-configuration

Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You are free to pick and choose jar dependencies outside of the starters. Spring Boot still does its best to auto-configure your application.

4.3.3. The “main” Method

The final part of our application is the main method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication class by calling runSpringApplication bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server. We need to pass Example.class as an argument to the run method to tell SpringApplication which is the primary Spring component. The args array is also passed through to expose any command-line arguments.

4.4. Running the Example

At this point, your application should work. Since you used the spring-boot-starter-parent POM, you have a useful run goal that you can use to start the application. Type mvn spring-boot:run from the root project directory to start the application. You should see output similar to the following:

$ mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.2.1.RELEASE)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)

If you open a web browser to localhost:8080, you should see the following output:

Hello World!

To gracefully exit the application, press ctrl-c.

4.5. Creating an Executable Jar

We finish our example by creating a completely self-contained executable jar file that we could run in production. Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.

Executable jars and Java

Java does not provide a standard way to load nested jar files (jar files that are themselves contained within a jar). This can be problematic if you are looking to distribute a self-contained application.

To solve this problem, many developers use “uber” jars. An uber jar packages all the classes from all the application’s dependencies into a single archive. The problem with this approach is that it becomes hard to see which libraries are in your application. It can also be problematic if the same filename is used (but with different content) in multiple jars.

Spring Boot takes a different approach and lets you actually nest jars directly.

To create an executable jar, we need to add the spring-boot-maven-plugin to our pom.xml. To do so, insert the following lines just below the dependencies section:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
The spring-boot-starter-parent POM includes <executions> configuration to bind the repackage goal. If you do not use the parent POM, you need to declare this configuration yourself. See the plugin documentation for details.

Save your pom.xml and run mvn package from the command line, as follows:

$ mvn package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.2.1.RELEASE:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

If you look in the target directory, you should see myproject-0.0.1-SNAPSHOT.jar. The file should be around 10 MB in size. If you want to peek inside, you can use jar tvf, as follows:

$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar

You should also see a much smaller file named myproject-0.0.1-SNAPSHOT.jar.original in the target directory. This is the original jar file that Maven created before it was repackaged by Spring Boot.

To run that application, use the java -jar command, as follows:

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.2.1.RELEASE)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)

As before, to exit the application, press ctrl-c.

 

Sample project: https://github.com/codinko/hello-boot

 

References:

http://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html

 

 

Spring Boot and PCF(Pivotal Cloud Foundry)

Let’s start creating a Spring Boot application..

  1. install STS ..download from here.. [Eclipse of your choice]
    https://spring.io/tools/sts
  2. Installing maven to run from command line
    https://codinko.wordpress.com/2015/12/02/maven-local-installation/3. Create a simple spring boot from maven archetype.mvn archetype:generate -DarchetypeGroupId=org.springframework.boot -DarchetypeArtifactId=spring-boot-sample-simple-archetype -DarchetypeVersion=1.0.2.RELEASE -DgroupId=com.codinko.code.cloud.springboot4 -DartifactId=cloud-springboot4 -Dversion=1.0.0-SNAPSHOTmvn-archetype-springboot.JPG

    // succesfully created..  Project created from Archetype in dir: D:\space.. BUILD SUCCESS

Import the project as maven project in your eclipse/STS workspace.

4. Create a Spring boot application in STS [Spring Tool Suite].

Reference: https://spring.io/blog/2015/03/18/spring-boot-support-in-spring-tool-suite-3-6-4

New -> Spring starter project -> packaging jar,type Maven, dependencies :web [support full stack web development including Tomcat and spring-webmvc]..

This is a web app. Let’s add a HelloController with a REST api that prints the name passed as parameter.
hello-controller.JPG
Right click on project and Run as Spring boot..

console1

http://localhost:8888/hello?name=codinko

In Application.properties, we have an entry :  server.port=8888

localhost8888-hello.JPG

Note: If you don’t have STS, the easy way is to use this online tool:    https://start.spring.io/

Notes:

Running a Boot App in STS
–  Spring boot apps created by the wizard come in two flavors ‘jar’ or ‘war’.
– The Starter wizard let’s you choose between them in its ‘packaging’ option.

A great feature of spring-boot is that you can easily create standalone ‘jar’ packaged projects that contain a fully functional embedded web server.

All you need to do to run your app, is run its Java Main type, just like you do any other plain Java application.

This is a huge advantage as you don’t have to mess around with setting up local or remote Tomcat servers, war-packaging and deploying.

If you really want to do things ‘the hard way’ you can still choose ‘war’ packaging.

However there’s really no need to do so because:

  • you can convert your ‘jar’ app to a ‘war’ app at any time
  • the Cloud Foundry platform directly supports deploying standalone Java apps.

 

Read more and Try this compulsory exercise mentioned here:
https://spring.io/blog/2015/03/18/spring-boot-support-in-spring-tool-suite-3-6-


Let’s push our project to github..

Go to github and create a repository.  let’s name it hello-boot.

The next page gives you these steps:
Open Git bash
cd existing_folder
git init
git remote add origin https://github.com/codinko/hello-boot.git
git commit -m “first commit”
git push -u origin master

When prompted, enter your credentials.
In Git repositories view, add existing local repo that you just created to view it from eclipse/ STS.

https://github.com/codinko/hello-boot


To understand a Spring Boot application that we just now created, its is mandatory to read this article. 

http://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html

Pending to read: http://projects.spring.io/spring-boot/

Cloud Foundry / PCF/ PWS

Cloud Foundry is an Open source PaaS, provides a fast and easy way to build, test, deploy and scale applications.
Pivotal Web Services, is an instance of PCF hosted by Pivotal.

  • Install Cloud Foundry Command Line Interface:
    https://docs.cloudfoundry.org/cf-cli/install-go-cli.html
    Test your installation by opening a terminal window and type cf. If your installation was successful, you can see the cf CLI help listing.
  • Register PWS [Pivotal Web Services] account.
    Pivotal provides free access for 1 year to Pivotal public cloud. Practice yourself!
    Create a Pivotal account – https://login.run.pivotal.io/login
  • Assuming you already have github account, and gitbash installed.

CLI Basics:
https://console.run.pivotal.io/tools

Login to the CLI
$ cf login -a api.run.pivotal.io
Get help in the CLI
$ cf help
Push an application
$ cf push your_app

Next Steps:
Install the CLI, Clone the app, Deploy the app to PWS thru CLI, view the logs:
Follow the below link to deploy a sample app [This one explains the project you can clone from github, how to push that app to PWS. Hence we are not repeating those steps here. Please read below one]

https://pivotal.io/platform/pcf-tutorials/getting-started-with-pivotal-cloud-foundry/introduction

cf auth email pwd  // this one worked from cygwin in windows

[The below one also works from windows terminal:
cf login -a https://api.run.pivotal.io –skip-ssl-validation -o yourorg -s yourspace ]

Then  cf push

$ cf push
FAILED
No org and space targeted, use ‘cf target -o ORG -s SPACE’ to target an org and space

– Go to your PWS account and find name of your ORG and SPACE

$ cf target -o my-org -s development

Now do $ cf push

 

cf-push-1.JPG

pws-org-space-screen1

Find logs:

cf logs cf-spring –recent


If you have a simple app created in STS, and you try to push the jar to PCF, it fails.
Because for deploying an app in PCF, the app needs to have  manifest.yml file.
When you do cf push, it is the manifest.yml that communicates to cf push, on how to deploy your application to PCF.

You can refer manifest.yml of the previous app, or refer the one below.
https://github.com/cloudfoundry-samples/hello-spring-cloud
https://github.com/cloudfoundry-samples/hello-spring-cloud/blob/master/manifest.yml

Lets create a sample app – https://github.com/codinko/hello-boot.git

Listing the HelloController.java, manifest.yml and application.properties for quick reference.

Let’s create the manifest.yml

Now do  cf login and cf push  application name

cf login -a https://api.run.pivotal.io –skip-ssl-validation -o codinko-org -s development

cd to project directory

cf push hello-boot

001-001.JPG

001-002

Let’s see the dashboard and our app from PCF

001-003

001-004

 

———————-

Connect to database:

https://pivotal.io/platform/pcf-tutorials/getting-started-with-pivotal-cloud-foundry/connect-a-database

How to connect this app to a mysql database/ add a mysql service – we’l cover soon..


 

 

 

Spring Batch introduction

Spring Batch is a framework that helps you to write robust batch jobs that are an essential part of every enterprise application.

  • Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management.
  • It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques.

Everything about and how to write Spring batch jobs can be found from this online resource – https:// www.petrikainulainen.net/spring-batch-the-ultimate-resource/

Spring Batch – Detailed

Read this first – https://codinko.wordpress.com/2017/04/16/spring-batch-introduction/

Basics:

  • Spring Batch uses a ‘Chunk Oriented’ processing style within its most common implementation.
  • Chunk oriented processing refers to reading the data one at a time, and creating ‘chunks’ that will be written out, within a transaction boundary.
  • One item is read in from an ItemReader, handed to an ItemProcessor, and aggregated.
  • Once the number of items read equals the commit interval, the entire chunk is written out via the ItemWriter, and then the transaction is committed.

https://docs.spring.io/spring-batch/docs/current/reference/html/images/chunk-oriented-processing.png

Below is a code representation of the same concepts shown above:

List items = new Arraylist();
for(int i = 0; i < commitInterval; i++){
    Object item = itemReader.read()
    Object processedItem = itemProcessor.process(item);
    items.add(processedItem);
}
itemWriter.write(items);

References: 

  • http://docs.spring.io/spring-batch/reference/html/configureStep.html
  • https://docs.spring.io/spring-batch/docs/current/reference/html/step.html#chunkOrientedProcessing

Understanding the concepts

The commit-interval defines how many items are processed within a single chunk. That number of items are read, processed, then written within the scope of a single transaction.

commit-inerval=10 means 10 items will be processed within each transaction

The page-size attribute on the paging ItemReader implementations (JdbcPagingItemReader for example) defines how many records are fetched per read of the underlying resource. So in the JDBC example, it’s how many records are requested with a single hit to the DB.

While there is no direct correlation between the two attributes, it’s typically considered a good idea to make them match, however they independently provide two knobs you can turn to modify the performance of your application.

if you have the page-size set to the same as the commit-interval, then it means a single commit for each page.

Before learning more read about these two important classes:

  1. JdbcPagingItemReader http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/database/JdbcPagingItemReader.html

Summary: ItemReader for reading database records using JDBC in a paging fashion.
The query is executed using paged requests of a size specified in AbstractPagingItemReader.setPageSize(int).

  1. PagingQueryProvider http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/database/PagingQueryProvider.html

Summary: Interface defining the functionality to be provided for generating paging queries for use with Paging Item Readers.
One method is generateFirstPageQuery()
java.lang.String generateFirstPageQuery(int pageSize)
Generate the query that will provide the first page, limited by the page size.
Parameters:
pageSize – number of rows to read for each page
Returns:
the generated query

For learning Spring Batch, the best tutorial is to learn from Spring docs!

https://docs.spring.io/spring-batch/reference/html/configureJob.html

https://docs.spring.io/spring-batch/docs/current/reference/html/job.html

Configuring  a Step:

Step is a domain object that encapsulates an independent, sequential phase of a batch job and contains all of the information necessary to define and control the actual batch processing.

The contents of any given Step are at the discretion of the developer writing a Job. A Step can be as simple or complex as the developer desires.

https://docs.spring.io/spring-batch/docs/current/reference/html/step.html#configureStep

https://docs.spring.io/spring-batch/docs/current/reference/html/images/step.png

 

The Commit Interval

A step reads in and writes out items, periodically committing using the supplied PlatformTransactionManager. With a commit-interval of 1, it will commit after writing each individual item. This is less than ideal in many situations, since beginning and committing a transaction is expensive. Ideally, it is preferable to process as many items as possible in each transaction, which is completely dependent upon the type of data being processed and the resources with which the step is interacting. For this reason, the number of items that are processed within a commit can be configured.

<job id="sampleJob">
    <step id="step1">
        <tasklet>
            <chunk reader="itemReader" writer="itemWriter" commit-interval="10"/>
        </tasklet>
    </step>
</job>

In the example above, 10 items will be processed within each transaction. At the beginning of processing a transaction is begun, and each time read is called on theItemReader, a counter is incremented. When it reaches 10, the list of aggregated items is passed to the ItemWriter, and the transaction will be committed.

 

References:

http://docs.spring.io/spring-batch/reference/html/configureStep.html

http://docs.spring.io/spring-batch/reference/html/configureJob.html

 

Database partitioning

https://www.oracle.com/database/partitioning/index.html

https://en.wikipedia.org/wiki/Partition_(database)

https://oracle-base.com/articles/8i/partitioned-tables-and-indexes

https://docs.oracle.com/database/121/VLDBG/GUID-F023D3ED-262F-4B19-950A-D3C8F8CDB4F4.htm#VLDBG1270

https://  www.mkyong.com/spring-batch/spring-batch-partitioning-example/

 

Spring REST and Swagger for REST documentation

Continuing with this post for developing Spring REST – Spring-REST

This post is exclusively on integrating Swagger to our Spring REST application.

 

Before we proceed, let’s see a glance of the final output to keep us energized.

swagger-ui-springrest

A live demo of what Swagger is capable of : swagger-live-demo-petstore

So what are the changes to be done in our application to integrate Swagger?

Let’s see..

 

Improvements/To-Do:

Use PUT instead of POST for updating employee.

Spring REST

From the scratch – Yes really from the scratch!!

  • First let’s download a web container – JBOSS or Apache Tomcat.
    I’ll go for Apache Tomcat as it’s easily available for download.

https://tomcat.apache.org/download-70.cgi

64-bit Windows zip  depending on your OS.

  • Now Lets download the eclipse IDE

http://eclipse.bluemix.net/packages/mars.2/data/eclipse-jee-mars-2-win32-x86_64.zip

 

  • Now let’s create the Spring Project.

You can either create a dynamic web project in eclipse, and add Maven and Spring capabilities.
[or]
Create a Maven project with ‘maven-archetype-webapp’ [An archetype which contains a sample Maven Webapp project.] and then add Spring capabilities.

Let’s look at some basic things before we really get our hands dirty.

Configure Maven [install in ur PC + configure in eclipse]

maven_env_system_variables

Open command prompt and run mvn -version

mvn-version

We forgot to set the JAVA_HOME. Let’s set it.

java_home_environment_var

Now execute the “mvn -version” command

mvn-version_success

Cool!

Since we’re doing the development in Eclipse IDE, Configure the maven and JRE in eclipse as well. [Window – preferences- Maven- installations  and Window – preferences- Java-Installed JREs, compilers]

If you’re creating the dynamic web project , then convert it to to a Maven project, by right click on the project and  Configure-convert to Maven project.

I went by the second way of creating the project, which is better –

  • Create a maven project with with ‘maven-archetype-webapp’ [An archetype which contains a sample Maven Webapp project.] and then add Spring capabilities.

 

 

Now add Spring nature to project. For that first let’s add Spring tools to the eclipse IDE by going to eclipse marketplace [Help – Eclipse marketplace]
eclipse-marketplace-spring

Once installed and eclipse is restarted, Right click on project and click Spring Tools – Add spring project nature.

That’s it.

Now let’s start the real fun :

  • Add the required maven dependencies for a Spring REST project  and develop three REST API’s

Well, don’t write any application without logging, So keep in mind to add the logging dependencies as well.

Eclipse generates a basic version of pom.xml and web.xml for you to build on top of it.

Run your project in the Apache tomcat server [Right click on project and choose run as server].

If you have postman plugin added to chrome [http://www.getpostman.com/] from chrome store, it is beautiful to see the output in your chrome browser after opening the postman app.

Output looks like this:

getAllEmployees

getEmployeeCertifications

 

 

The Complete code is here:

Project Structure in eclipse looks like this:

springrest-structure

 

 

 

 

 

Spring Framework version 4 and 3 features

SPRING 4.0

  • Released in December 2013

Version 4.0 is the latest major release of the Spring Framework and the first to fully support Java 8 features. You can still use Spring with older versions of Java, however, the minimum requirement has now been raised to Java SE 6.

Spring 4.0 Features

  • JSR-335 Lambda expressions
  • JSR-310 Date-Time value types for Spring data binding and formatting.
  • JSR-343 JMS 2.0.
  • JSR-338 JPA 2.1.
  • JSR-349 Bean Validation 1.1.
  • JSR-236 Java EE 7 Enterprise Concurrency support.
  • JSR-356 Spring’s WebSocket endpoint mode.
  • Configuring and implementing Spring style application using Groovy 2. Also they specify that first class support for the Groovy applications.
  • Also spring plans to add the HATEOS (Hypermedia as the Engine of Application State) support for REST APIs.

An important feature to highlight in Spring4.0 is the @RestController annotation to support REST API’s .

@RestController annotation is inherited from the @Controller annotation. Prior to the version 4.0, all the Spring MVC components has to use the common @Controller annotation to mark that as the controller servlet. When you implement a RESTful web services, the response would be always sent with the response body. To make this simple, Spring 4.0 has provided a specialized version of controller.

Here is the definition of the @RestController implementation.

Spring-4.0-RestController

Spring docs says:

A convenience annotation that is itself annotated with @Controller and @ResponseBody. Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

@ResponseBody – As of version 4.0 this annotation can also be added on the type level in which case is inherited and does not need to be added on the method level.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/new-in-4.0.html

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/new-in-4.1.html

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/new-in-4.2.html

SPRING 3.0, 3.1, 3.2

  • Spring 3.0 was first released in December 2009.
  • Spring 3.1 followed in December 2011.
  • Spring 3.2.2 was released in March 2013. Along with this announcement is the release of Spring Framework 3.2.3, containing bug fixes and OpenJDK 8 runtime support.

 

Java SE and Java EE Support

The Spring Framework is now based on Java 5, and Java 6 is fully supported.

Furthermore, Spring is compatible with J2EE 1.4 and Java EE 5, while at the same time introducing some early support for Java EE 6.

This is a list of new features for Spring 3.0.

  • Spring Expression Language
  • IoC enhancements/Java based bean metadata
  • General-purpose type conversion system and field formatting system
  • Object to XML mapping functionality (OXM) moved from Spring Web Services project
  • Comprehensive REST support
  • @MVC additions
  • Declarative model validation
  • Early support for Java EE 6
  • Embedded database support

The first milestone release of Spring 3.1 has the following features

  • Bean definition profiles
  • Unified property management through Spring’s new Environment abstraction
  • Enhancements to Java-based configuration with @Feature methods
  • Expanded MVC namespace support and a Java-based configuration equivalent
  • Streaming support and new interception model for the RestTemplate API
  • Comprehensive caching support
  • New c: XML namespace for concise configuration of constructor injection

And a lot more. please go through the below links:

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.0.html

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.1.html

http://spring.io/blog/2011/02/11/spring-framework-3-1-m1-released/

Spring 3.2 features

  1. Spring MVC Test Framework
  2. Asynchronous MVC processing on Servlet 3.0
  3. custom @Bean definition annotations in @Configuration classes
  4. @Autowired and @Value to be used as meta-annotations
  5. Concurrency refinements across the framework
  6. loading WebApplicationContexts in the TestContext framework
  7. JCache 0.5 (JSR-107)

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.2.html

 

 

Olderposts

Copyright © 2019 Codinko- Java Coding Tutorials

Theme by Anders NorenUp ↑