37
Spring Boot - By Vinay Prajapati

Spring boot

Embed Size (px)

Citation preview

Page 1: Spring boot

Spring Boot - By Vinay Prajapati

Page 2: Spring boot
Page 4: Spring boot

•••••••

––––

Page 5: Spring boot

•••

Page 6: Spring boot

@Controllerclass Example {

@RequestMapping("/")@ResponseBody public String helloWorld() {

"Hello Spring boot audience!!!"}

}

Page 7: Spring boot

// import org.springframework.web.bind.annotation.Controller// other imports ...// @Grab("org.springframework.boot:spring-boot-web-starter:0.5.0")

// @EnableAutoConfiguration@Controllerclass Example { @RequestMapping("/") @ResponseBody public String hello() { return "Hello World!"; }

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

Page 8: Spring boot

•••

•–

•–

––––––

Page 9: Spring boot

@Grab('spring-boot-starter-security')@Grab('spring-boot-starter-actuator')@Grab('spring-boot-starter-jetty')@Controllerclass Example {

@RequestMapping("/")@ResponseBodypublic String helloWorld() {

return "Hello Audience!!!"}

}

//security.user.name//security.user.password

//actuator endpoints: /beans, /health, /mappings, /metrics etc.

Page 10: Spring boot
Page 11: Spring boot

apply plugin: 'groovy'apply plugin: 'idea'apply plugin: 'spring-boot'

buildscript { repositories { mavenCentral()} dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.8.RELEASE") classpath 'org.springframework:springloaded:1.2.0.RELEASE' }}

repositories { mavenCentral() }

dependencies { compile 'org.codehaus.groovy:groovy-all' compile 'org.springframework.boot:spring-boot-starter-web'}

Page 12: Spring boot

Exercise- Use actuator starter POM in gradle application just created

- Use security starter POM in gradle application just created

- Changing the default embedded servlet container and the port

Page 13: Spring boot

13

$ gradle build$ java -jar build/libs/mymodule-0.0.1-SNAPSHOT.jar

//...apply plugin: 'war'war { baseName = 'myapp' version = '0.5.0'}//....configurations { providedRuntime}

dependencies { compile("org.springframework.boot:spring-boot-starter-web") providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")// ...}$ gradle war

Page 14: Spring boot

••

14

app: name: Springboot+Config+Yml+Demo version: 1.0.0server: port: 8080settings: counter: 1---spring: profiles: developmentserver: port: 9001

Page 15: Spring boot

15

export SPRING_PROFILES_ACTIVE=developmentexport SERVER_PORT=8090gradle bootRunjava -jar build/libs/demo-1.0.0.jar

java -jar -Dspring.profiles.active=development build/libs/dem-1.0.0.jarjava -jar -Dserver.port=8090 build/libs/demo-1.0.0.jar

Page 16: Spring boot

16

import org.springframework.boot.context.properties.ConfigurationPropertiesimport org.springframework.stereotype.Component@Component@ConfigurationProperties(prefix = "app")class AppInfo { String name String version}

import org.springframework.beans.factory.annotation.Valueimport org.springframework.stereotype.Component@Componentclass AppConfig { @Value('${app.name}') String appName

@Value('${server.port}') Integer port}

Page 17: Spring boot
Page 18: Spring boot

1. A /config subdir of the current directory. 2. The current directory3. A classpath /config package4. The classpath root

Don’t forget commandLine. It’s the Master here.

Page 19: Spring boot

2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52

2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext

$ java -jar myapp.jar --debug

Page 20: Spring boot

logging.file logging.path Example Description

(none) (none) Console only logging.

Specific file (none) my.log Writes to the specified log file. Names can be an exact location or relative to the current directory.

(none) Specific directory /var/log Writes spring.log to the specified directory. Names can be an exact location or relative to the current directory.

Page 21: Spring boot

logging.level.*: DEBUG_LEVEL

E.g.

logging.level.intellimeet: ERROR

Page 22: Spring boot

ID Description Sensitive

autoconfig Displays an auto-configuration report showing all auto- configuration candidates and the reason why they ‘were’ or ‘were not’ applied.

true

beans Displays a complete list of all the Spring beans in your application. true

configprops Displays a collated list of all @ConfigurationProperties. true

dump Performs a thread dump. true

env Exposes properties from Spring’s ConfigurableEnvironment. true

health Shows application health information (a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated).

false

info Displays arbitrary application info. false

metrics Shows ‘metrics’ information for the current application. true

mappings Displays a collated list of all @RequestMapping paths. true

shutdown Allows the application to be gracefully shutdown (not enabled by default). true

trace Displays trace information (by default the last few HTTP requests). true

Page 23: Spring boot

The prefix #endpoints + . + name” is used to uniquely identify the endpoint that is being configured.

E.g.endpoints.beans.id=springbeans endpoints.beans.sensitive=false endpoints.shutdown.enabled=true

Page 24: Spring boot

:•

compile 'mysql:mysql-connector-java:5.1.6'compile 'org.springframework.boot:spring-boot-starter-jdbc'compile 'org.springframework.boot:spring-boot-starter-data-jpa'

spring.datasource.url= jdbc:mysql://localhost/springbootspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driverClassName=com.mysql.jdbc.Driverspring.jpa.hibernate.ddl-auto=create-drop

import javax.persistence.Entityimport javax.persistence.Idclass City{@Id String id, String name , String stateprotected City() {}public City(String name, String state) { this.name = name this.state = state}}

Page 25: Spring boot

• import org.springframework.data.mongodb.repository.MongoRepository public interface CityRepository extends CrudRepository<City, Long> {}

•@Autowired CityRepository cityRepositorycityRepository.save(new City(id:'1',name: 'Noida',state: 'UP'))cityRepository.findAll()cityRepository.count()

Page 26: Spring boot

(A Glimpse)•••••••

26

Page 27: Spring boot

••

27

compile "org.grails:grails-gsp-spring-boot:1.0.0.RC1" compile "org.grails:grails-web:2.4.0.M2"

Page 28: Spring boot

28

@RequestMapping("/show/{id}")public ModelAndView show(@PathVariable Long id) { Person person = Person.read(id) if (person) { new ModelAndView("/person/show", [personInstance: Person.get(id)]) } else { log.info "No entity fount for id : " + id new ModelAndView("redirect:/person/list") } }

Page 29: Spring boot

29

@[email protected] ApplicationTagLib { static namespace = "app" def paginate = { attrs -> String action = attrs.action Integer total = attrs.total Integer currentPage = attrs.currentPage ?: 1 Integer pages = (total / 10) + 1 out << render(template: "/shared/pagination", model: [action: action, total: total, currentPage: currentPage, pages: pages] ) }}

<app:paginate total="${personInstanceCount ?: 0}" currentPage="${currentPage}" action="/person/list"/>

Page 30: Spring boot

- Messaging (JMS)- NOSQL / SQL database support- Mailing- Testing - Monitoring and Management using JMX- Hot Swapping - reloading content on run

time

Page 31: Spring boot

Page 32: Spring boot

com +- example +- myproject +- Application.java(Main class) | +- domain

| +- Customer.java | +- CustomerRepository.java

| +- service

| +- CustomerService.java | +- web +- CustomerController.java

Fig.: Typical structure to be followed

Page 33: Spring boot

Miscellaneous- Enabling Disabling the Banner

- Changing the Banner

(http://www.kammerl.de/ascii/AsciiSignature.php)

- Adding event Listeners

- Logging startup info

Page 34: Spring boot
Page 35: Spring boot

● Idea behind Spring Boot.● It’s key Features● Easy start with Spring Boot using CLI.● .● Using Spring boot with build tools - gradle, maven.● Packaging executable jar files / war files.● Environment AKA Profile● Persisting data using Spring Data ● Next level persistence using GORM● Creating Views a Glimpse● Some Misc.

Page 36: Spring boot

36

Page 37: Spring boot