Showing posts with label SpringBoot. Show all posts
Showing posts with label SpringBoot. Show all posts

24 April 2020

Maven Fundamentals (Course on Plural Sight):

Maven

  • Works with Eclipse/ net beans.
  • Preferred choice for working with build tools like Cruise Control/Bamboo.
  • Ant is build on top of Java and XML in procedural way. Ant developed to be replacement for unix build tool Make. You need to define everything you want to do like clean/clear/cleanup etc. No inheritance, no reuse. Ant is scripting tool.
  • using Maven it is full fledged build tool.
  • transitive dependencies and capable to achieve inheritance in projects. In Maven we have pom.xml unlike build.xml in ant. Maven is interested in managing entire project life cycle.
  • Copy apach-maven-3.5.0 and add bin directory of maven to Path environment variable. run below command to know the version of maven
    mvn -version
  • Create a General project in STS and name it TestCalculator and add a file to the project with name pom.xml (project object model). and create a java file in that with some text printing on to the console.
    contents of pom.xml
<project>
<groupId>com.pluralsight</groupId>
<artifactId>TestCalculator</artifactId>
<version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>

</project>
  • now navigate to the workspace folder from command prompt and run
mvn clean
mvn compile
then
go to
cd target/classes
and run below command to print output Madhu
java TestCalculator
  • run below command to create jar file as per pom.xml
    mvn package
all java code goes to src/main/java directory All test code is in src/test/java . All other language code is in src/main/groovy directory. All classes after compiling goes to target/classes/

some maven commands useful:

mvn clean package
mvn install
this will run package command and move the .jar to the C:\users\talakokm.m2\repository in that with group name set in pom.xml
even dependencies are copied here

Goals

clean
compile: compile src/main directory and move the classes to target/classes.
package: create jar/ear/war
install:Run package command and installs to local repository.
deploy: run install command and deploys to corporate repository.

pom.xml contents

Project is of 4 parts
groupId: is used in packaging of application like com.cdk
artifaceId: is application name.
version: version number of application.
packaging: is to mention how we want to package the application for example .war/.ear/.jar.
Dependencies
transitive dependencies will be pulled by Maven , it needs 3 things
groupId
artifactId
version
Example:
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang<artifactId>
<version>2.1</version>
</dependency>
</dependencies>
Add below build tag to pom.xml to set final name of our application while building application:
<build>
<finalName>foo</finalName>
</build>
now foo.jar is created in target directory with name foo.jar

Transitive dependencies:

Is the main reason why we use Maven.
Example: Add below dependency it will download all transitive dependencies.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<versions>4.1.6.Final</version>
<scope>compile</scope>
</dependency>

Scope types in dependency:
There are six types of scopes available in dependencies.
compile - default scope. available everywhere
provide - like compile. available everywhere but not included in final artifact.
runtime - available only in runtime.
test - only available for test compilation/execution phase.
SNAPSHOT has special meaning. every compile or run picks up latest code.

Dependency Repository:

is where we store/download all our dependencies
specifying our own repository
<repositories>
<repository>
<id>spring-snapshot</id>
<name>Spring Maven SNAPSHOT Repository</name>
<url>http://repo.springsource.org/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>

Convert project to Maven Project via STS

in STS , select the project and right click and select configure --> convert to Maven project.

Adding dependencies:

using pom viewer we can edit pom.xml
also using dependencies tab we can update/add dependencies. dependency hierarchy automatically updated after save.

Effective POM

there is tab called Effective POM on pom.xml useful for debugging pom.xml to know what pom is doing.

13 April 2020

Creating your first Spring Boot application

Refence: Plural Sight Course : Creating your first Spring Boot application:

create a maven project with by setting groupId as com.boot and artifactId as das-boot and version as 0.0.1-SNAPSHOT and packaging as jar.

we need to add parent to pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.1.RELEASE</version>
</parent>

and in dependencies of pom.xml add
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

go to sr/main/java/App.java
and add
@SpringBootApplication
before the class
in the main method add
SpringApplication.run(App.class, args);

in src/main/java create package with names
controller
model
repository
service
under controller create a file HomeController.java
and add below content


package com.boot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

    @RequestMapping("/")
    public String home() {
        return "Das Boot, reporting for duty!";
    }
}
Right click app.java and select run as java application to see response at localhost:8080




Learning Path for Spring Boot
1. Maven Fundamentals - done
2. Spring Fundamentals - done
3. Introduction to Spring MVC4
4. Spring Security Fundamentals
5. Spring with JPA and Hibernate
6. Getting Started with Spring Data JPA
7. Getting  Started with Spring Data REST

for references go to spring.io.
To generate new basic project go to start.spring.io (web initializer).
command line Spring Boot CLI, which inturn uses api provided by start.spring.io.
https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-installing-spring-boot.html#getting-started-installing-the-cli

How does spring boot work?
@SpringBootApplication :A convinience annotation that wraps commonly used annotations with spring boot.
@Configuration : Spring configuration on startup. various configurations used by string.
@EnableAutoConfiguration: any components it finds in class path, it wires automatically to spring boot.
@ComponentScan : scans project for spring components



to know more information about any annotation, click on annotation and press F3. It will give more information.

Why move to containerless deployments?
in container deployments we have to deploy our java application to JBOSS or Tomcat container.
Problems with Container Deployments:
1. container need to be setup for each environment (pre-setup and configuration).
2. Need to use deployment descriptor files like web.xml to tell container how to work.
3. container envioronment settings which are external to your application.
Use of Application Deployments (Containerless deployments)
1. Runs anywhere java is setup (like cloud deployments)
2. Container is embedded and the app directs how the container works.
3. runs as plain java application which eases debugging.
Spring boot uses Embedded container or container less deployments.

=> We can copy the ui related files like angular code directly to src/main/resources/public directory, right click on project and select refresh. To make src/main/resources as class path resource, right click select Maven -> Update Project (Alt+F5).
=> Any change in html file in src/main/resources/public directory is reflected immediately.
=> All rest features in spring boot application are provided by spring mvc.
application.properties is the file we can set properties of application when we move one environment to another environment.
maven configured the build such that src/main/resources is in class path. so create application.properties in this folder. some example of application properties is to increase loggging level.
Example:
logging.level.org.springframework.web=DEBUG
server.port=8181
we can introduce some more files like application-test.properties or application-prod.properties after creating them in same directory as application.properties.
to pick this custom properties file, right click on project → select run as → Run Configurations and go to Arguments tab to add VM arguments as -Dspring.profiles.active=test
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
=> Search for spring boot common application properties in google to know what are all the properties available.

add below dependency to pom.xml if you want to use database
      <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
      </dependency>


after you rerun the application u would see log statement like
2018-02-23 16:04:08.761  INFO 8112 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.11.Final}

Add below properties to application.properties and restart the application to use h2 database.
spring.h2.console.enabled=true
spring.h2.console.path=/h2

login to db like http://localhost:8080/h2 with sa/sa credentials to connect to web based db available to spring boot application.

Add below code to application.properties and restart the application to login with sa and blank password, login and create table
spring.datasource.url=jdbc:h2:file:~/dasboot
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

some more settings
spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1

for flyway database setting add below dependency in pom.xml:
      <dependency>
          <groupId>org.flywaydb</groupId>
          <artifactId>flyway-core</artifactId>
      </dependency>
------------------------------------------------------------------------------------------------------------
Add @Loggable to know time taken by the specific method in console of STS:

{"@timestamp":"2018-02-01T17:51:17.366+05:30","@version":1,"message":"Total execution time taken by getClientReport ( [E200500] ) method is 119137 ms","logger_name":"com.xxxworks.reporting.serviceapi.repo.ChrDataRepoImpl","thread_name":"http-nio-8080-exec-1","level":"INFO","level_value":20000,"HOSTNAME":"HYD-TALAKOM","customFields":"{\"vendor\": \"CK.PSP\"}","vendor":"CK.PSP"}
-----------------------------------------------------------------------------------------------------------

References:
http://www.adeveloperdiary.com/java/spring-boot/create-restful-webservices-using-spring-boot/
http://www.programming-free.com/2014/07/spring-data-rest-with-angularjs-crud.html
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-build-an-executable-archive-with-ant

Logging:
https://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/html/howto-logging.html
http://blog.netgloo.com/2014/12/11/logging-in-spring-boot/