Download - Zero Effort Spring

Transcript
Page 1: Zero Effort Spring

Spring BootDave Syer, Phil Webb, 2013Twitter: @david_syer, @phillip_webbEmail: [dsyer, pwebb]@gopivotal.com

(Introduction to Spring Boot)

1 of 37 03/09/13 14:50

Page 2: Zero Effort Spring

2 of 37 03/09/13 14:50

Page 3: Zero Effort Spring

Agenda

Quick overview of goals and high level features

Getting started demo

Behind the scenes of @EnableAutoConfiguration

Adding new features to Spring Boot

3 of 37 03/09/13 14:50

Page 4: Zero Effort Spring

Introduction

Spring Boot:

Focuses attention at a single point (as opposed to large collection ofspring-* projects)

A tool for getting started very quickly with Spring

Common non-functional requirements for a "real" application

Exposes a lot of useful features by default

Gets out of the way quickly if you want to change defaults

An opportunity for Spring to be opinionated

4 of 37 03/09/13 14:50

Page 5: Zero Effort Spring

Focus Attention

5 of 37 03/09/13 14:50

Page 6: Zero Effort Spring

Spring Boot Goals

Provide a radically faster and widely accessible getting startedexperience

Be opinionated out of the box, but get out of the way quickly asrequirements start to diverge from the defaults

Provide a range of non-functional features that are common to largeclasses of projects (e.g. embedded servers, security, metrics, healthchecks, externalized configuration)

Absolutely no code generation and no requirement for XMLconfiguration

6 of 37 03/09/13 14:50

Page 7: Zero Effort Spring

Getting Started Really Quickly

app.groovy:

@Controllerclass Application { @RequestMapping('/') @ResponseBody String home() { 'Hello World!' }}

then

$ spring run app.groovy

7 of 37 03/09/13 14:50

Page 8: Zero Effort Spring

Getting Started

DEMO

8 of 37 03/09/13 14:50

Page 9: Zero Effort Spring

Getting Started In Java

Application.java:

...@Controller@EnableAutoConfigurationpublic class Application {

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

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

}

9 of 37 03/09/13 14:50

Page 10: Zero Effort Spring

Getting Started In Java

...then

$ mvn package$ java -jar target/*.jar

(or use gradle equivalents)

10 of 37 03/09/13 14:50

Page 11: Zero Effort Spring

Getting Started

DEMO

11 of 37 03/09/13 14:50

Page 12: Zero Effort Spring

What Just Happened?

SpringApplication: convenient way to write a main() methodthat loads a Spring context

@EnableAutoConfiguration: optional annotation that adds stuff toyour context, including...

EmbeddedServletContainerFactory: added to your context if aserver is available on the classpath

CommandLineRunner: a hook to run application-specific code afterthe context is created

JarLauncher was added to the JAR file

12 of 37 03/09/13 14:50

Page 13: Zero Effort Spring

Spring Boot Modules

Spring Boot - main library supporting the other parts of Spring Boot

Spring Boot Autoconfigure - single @EnableAutoConfigurationannotation creates a whole Spring context

Spring Boot Starters - a set of convenient dependency descriptorsthat you can include in your application.

Spring Boot CLI - compiles and runs Groovy source as a Springapplication

Spring Boot Actuator - comman non-functional features that make anapp instantly deployable and supportable in production

Spring Boot Tools - for building and executing self-contained JAR andWAR archives

Spring Boot Samples - a wide range of sample apps

13 of 37 03/09/13 14:50

Page 14: Zero Effort Spring

Spring Boot Module Relations

14 of 37 03/09/13 14:50

Page 15: Zero Effort Spring

Binding to Command LineArguments

SpringApplication binds its own bean properties to command linearguments, and then adds them to the Spring Environment, e.g.

$ java -jar target/*.jar --server.port=9000

15 of 37 03/09/13 14:50

Page 16: Zero Effort Spring

Externalizing Configuration toProperties

Just put application.properties in your classpath, e.g.

application.properties

server.port: 9000

16 of 37 03/09/13 14:50

Page 17: Zero Effort Spring

Using YAML

Just put application.yml in your classpath

application.yml

server: port: 9000

Both properties and YAML add entries with period-separated paths to theSpring Environment.

17 of 37 03/09/13 14:50

Page 18: Zero Effort Spring

Binding ExternalConfiguration To Beans

MineProperties.java

@ConfigurationProperties(prefix="mine")public class MinePoperties { private Resource location; private boolean skip = true; // ... getters and setters}

application.properties

mine.location: classpath:mine.xmlmine.skip: false

18 of 37 03/09/13 14:50

Page 19: Zero Effort Spring

Customizing ConfigurationLocation

Set

spring.config.name - default application, can be comma-separated list

spring.config.location - a Resource path, overrides name

e.g.

$ java -jar target/*.jar --spring.config.name=sagan

19 of 37 03/09/13 14:50

Page 20: Zero Effort Spring

Spring Profiles

Activate external configuration with a Spring profilefile name convention e.g. application-development.propertiesor nested documents:

application.yml

defaults: etc...---spring: profiles: development,postgresqlother: stuff: more stuff...

Set the default spring profile in external configuration, e.g:application.properties

spring.profiles.active: default,postgresql

20 of 37 03/09/13 14:50

Page 21: Zero Effort Spring

Adding some AutoconfiguredBehaviour

Extend the demo and see what we can get by just modifying the classpath,e.g.

Add an in memory database

Add a Tomcat connection pool

21 of 37 03/09/13 14:50

Page 22: Zero Effort Spring

Adding A UI with Thymeleaf

Add Thymeleaf to the classpath and see it render a view

Spring Boot Autoconfigure has added all the boilerplate stuff

Common configuration options via spring.thymeleaf.*, e.g.spring.thymeleaf.prefix:classpath:/templates/(location of templates)spring.tjymeleaf.cache:true (set to false to reloadtemplates when changed)

Extend and override:add Thymeleaf IDialect beansadd thymeleafViewResolveradd SpringTemplateEngineadd defaultTemplateResolver

22 of 37 03/09/13 14:50

Page 23: Zero Effort Spring

Currently AvailableAutoconfigured Behaviour

Embedded servlet container (Tomcat or Jetty)

DataSource and JdbcTemplate

JPA

Spring Data JPA (scan for repositories)

Thymeleaf

Batch processing

Reactor for events and async processing

Actuator features (Security, Audit, Metrics, Trace)

23 of 37 03/09/13 14:50

Page 24: Zero Effort Spring

Building a WAR

We like launchable JARs, but you can still use WAR format if you prefer.Spring Boot Tools take care of repackaging a WAR to make it executable.

If you want a WAR to be deployable (in a "normal" container), then youneed to use SprinBootServletInitializer instead of or as well asSpringApplication.

24 of 37 03/09/13 14:50

Page 25: Zero Effort Spring

The Actuator

Adds common non-functional features to your application and exposesMVC endpoints to interact with them.

Security

Secure endpoints: /metrics, /health, /trace, /dump,/shutdown, /beans

Audit

/info

If embedded in a web app or web service can use the same port or adifferent one (and a different network interface).

25 of 37 03/09/13 14:50

Page 26: Zero Effort Spring

Adding Security

Use the Actuator

Add Spring Security to classpath

26 of 37 03/09/13 14:50

Page 27: Zero Effort Spring

Logging

Spring Boot provides default configuration files for 3 common loggingframeworks: logback, log4j and java.util.logging

Starters (and Samples) use logback

External configuration and classpath influence runtime behaviour

LoggingApplicationContextInitializer sets it all up

27 of 37 03/09/13 14:50

Page 28: Zero Effort Spring

Customizing theApplicationContextCreation

Add external configuration (System properties, OS env vars, configfile, command line arguments)

Add ApplicationContextInitializer implementations andenable in application.properties

28 of 37 03/09/13 14:50

Page 29: Zero Effort Spring

Customizing the@EnableAutoConfigurationBehaviour

Add JAR with META-INF/spring.factories entry forEnableAutoConfiguration

All entries from classpath merged and added to context

29 of 37 03/09/13 14:50

Page 30: Zero Effort Spring

Customizing the CLI

Uses standard Java META-INF/services scanning

CompilerAutoConfiguration: add dependencies and imports

CommandFactory: add commands via a custom CommandFactoryin META-INF/services

E.g. can add script commands (written in Groovy)

$ spring foo ...

Looks for foo.groovy in ${SPRING_HOME}/bin and${SPRING_HOME}/ext by default

30 of 37 03/09/13 14:50

Page 31: Zero Effort Spring

Customizing Servlet ContainerProperties

Some common features exposed with external configuration, e.g.server.port (see ServerProperties bean)

Add bean of type EmbeddedServletContainerCustomizer - allinstances get a callback

Add bean of type EmbeddedServletContainerFactory(replacing auto-configured one)

31 of 37 03/09/13 14:50

Page 32: Zero Effort Spring

Spring Boot Loader

Motivation: existing solutions for executable JAR are not very robust;executable WAR is very tricky to create.

Response: JarLauncher and WarLauncher with specializedClassLoader implementations that can find resources in nested JARs(e.g. lib/*.jar or WEB-INF/lib/*.jar)

32 of 37 03/09/13 14:50

Page 33: Zero Effort Spring

Maven and Gradle Tooling

Create an executable archive (JAR or WAR)

Maven plugin (using spring-boot-starter-parent):${project.groupId} spring-boot-maven-plugin$ mvn package

Gradle plugin:apply plugin: 'spring-boot'$ gradle repackage

33 of 37 03/09/13 14:50

Page 34: Zero Effort Spring

Testing with Spring Test(MVC)

SpringApplication is an opinionated creator of anApplicationContext, but most of the behaviour is encapsulated inApplicationContextInitializer implementations. To reproduce thebehaviour of you app in an integration test it is useful to duplicate thosefeatures you can use the corresponding initializers.

Example if you have externalized configuration:

34 of 37 03/09/13 14:50

Page 35: Zero Effort Spring

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes =IntegrationTestsConfiguration.class, initializers =ConfigFileApplicationContextInitializer.class)public class IntegrationTests {

// Normal Spring Test stuff

}

35 of 37 03/09/13 14:50

Page 36: Zero Effort Spring

Links

https://github.com/SpringSource/spring-boot Spring Boot on Github

https://projects.spring.io/spring-boot Documentation

http://spring.io/blog

http://dsyer.com/decks/spring-boot-intro.md.html

Twitter: @david_syer

Email: [email protected]

36 of 37 03/09/13 14:50

Page 37: Zero Effort Spring

Spring Boot Intro - END

37 of 37 03/09/13 14:50


Top Related