Spring Boot
-
Upload
pei-tang-huang -
Category
Technology
-
view
1.967 -
download
4
Transcript of Spring Boot
WhoAmI?
• Youwillfindmeherehttps://github.com/tan9
http://stackoverflow.com/users/3440376/tan9
• MyJavaexperience• JavaandJavaEEdevelopment– 8+years• SpringFramework– 6+years• SpringBoot– 1.5years
2
BeforeWe Get Started…
• Jointhechannel:http://bit.do/spring-boot• Directlink:https://gitter.im/tan9/spring-boot-training
• SigninusingyourGitHub account• Orsignuprightnow!
3
SpringFramework
• InversionofControl(IoC)container• DependencyInjection(DI)• Beanlifecyclemanagement• Aspect-OrientedProgramming(AOP)
• “Plumbing”ofenterprisefeatures• MVCw/RESTful,TX,JDBC,JPA,JMS…
• Neutral• Doesnotimposeanyspecificprogrammingmodel.• Supportsvariousthird-partylibraries.
5
Spring2.5JavaConfig
• FavorJavaAnnotation (introducedinJavaSE5)• @Controller, @Service and@Repository• @Autowired
• ThinXMLconfigurationfile
6
<context:annotation-config/><context:component-scan
base-package="com.cht"/>
JavaConfig KeepEvolving
• @Bean&@Configuration since3.0• GetridofXMLconfigurationfiles.
• @ComponentScan,@Enable* and@Profile since3.1• WithWebApplicationInitializer poweredbyServlet3,saygoodbyetoweb.xml too.
• @Conditional since4.0• We’reabletofilterbeansprogrammatically.
7
MavenBill-Of-Materials(BOM)
• KeeplibraryversionsinONEplace.• ImportfromPOM’s<dependencyManagement>section.
• Declaredependencies without<version>:
8
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId>
</dependency>
Things GettingComplicated
• Springseldomdeprecatesanything• Andofferslittleopinionorguidance.• Olderapproachesremainatthetopinsearchresults.
• Bootstrappingcanbepainful• Duetothesheersizeandgrowthrateoftheportfolio.
• Springisanincrediblypowerfultool…• Onceyougetitsetup.
Shouldyouusespringboot inyournextproject?- StevePerkinshttps://steveperkins.com/use-spring-boot-next-project/ 9
ThoughtWorks TechnologyRadar
11ThoughtWorks Techonlogy RaderApril‘16https://www.thoughtworks.com/radar
SpringBoot
• Opinionated• Convention overconfiguration.
• Production-readynon-functionalfeatures• Embeddedservers,security,metrics,healthchecks…
• Speedup• Designedtogetyouupandrunningasquicklyaspossible.
• PlainJava• NocodegenerationandnoXMLconfiguration.
12
SystemRequirements
• SpringBoot1.3requiresJava7+ bydefault• Java8isrecommendedifatallpossible.• CanusewithJava6withsomeadditionalconfiguration.
• Servlet3.0+ container• Embedded Tomcat7+,Jetty8+,Undertow1.1+.• OracleWebLogicServer12corlater.• IBMWebSphereApplicationServer8.5orlater.• JBoss EAP6orlater.
13
BootWithApacheM
aven
14
<project><modelVersion>4.0.0</modelVersion><groupId>com.cht</groupId><artifactId>inception</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>1.3.5.RELEASE</version>
</parent>
<!-- 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>
StarterPOMs
• Makeeasytoaddjarstoyourclasspath.• spring-boot-starter-parent• ProvidesusefulMavendefaults.• Definesversion tagsfor“blessed”dependencies.
• spring-boot-starter-*• Providesdependenciesyouarelikelytoneedfor*.
15
FirstClass
package com.cht.inception;
import org.springframework.boot.*;import org.springframework.boot.autoconfigure.*;import org.springframework.web.bind.annotation.*;
@RestController@EnableAutoConfigurationpublic class Application {
@RequestMapping("/")String home() {
return "Hello World!";}
public static void main(String[] args) {SpringApplication.run(Application.class, args);
}}
16
mvn spring-boot:run
17
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v1.3.5.RELEASE)
2016-07-03 23:38:04.683 INFO 93490 --- [ main] com.cht.inception.Application : Starting Application on Huangs-MBP with PID 93490 (/Users/tang/Desktop/spring-boot-training/target/classes started by tang in /Users/tang/Desktop/spring-boot-training)2016-07-03 23:38:04.685 INFO 93490 --- [ main] com.cht.inception.Application : No active profile set, falling back to default profiles: default2016-07-03 23:38:04.718 INFO 93490 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@63f60873: startup date [Sun Jul 03 23:38:04 CST 2016]; root of context hierarchy2016-07-03 23:38:05.482 INFO 93490 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)2016-07-03 23:38:05.491 INFO 93490 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat2016-07-03 23:38:05.491 INFO 93490 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.332016-07-03 23:38:05.548 INFO 93490 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2016-07-03 23:38:05.548 INFO 93490 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 833 ms2016-07-03 23:38:05.702 INFO 93490 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]2016-07-03 23:38:05.833 INFO 93490 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@63f60873: startup date [Sun Jul 03 23:38:04 CST 2016]; root of context hierarchy2016-07-03 23:38:05.876 INFO 93490 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.cht.inception.Application.home()2016-07-03 23:38:05.879 INFO 93490 --- [ main] 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.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2016-07-03 23:38:05.879 INFO 93490 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)2016-07-03 23:38:05.898 INFO 93490 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-07-03 23:38:05.898 INFO 93490 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-07-03 23:38:05.921 INFO 93490 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-07-03 23:38:05.986 INFO 93490 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup2016-07-03 23:38:06.032 INFO 93490 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2016-07-03 23:38:06.036 INFO 93490 --- [ main] com.cht.inception.Application : Started ⏎Application in 1.529 seconds (JVM running for 4.983)
ApplicationProperties
• Placeapplication.yaml inclasspath• Forexample:• Configuringembeddedservercanbeaseasyas:
19
server:address: 127.0.0.1port: 5566
YAML(YAMLAin’t MarkupLanguage)
• SupersetofJSON.• UTF-8!• Reallygoodforhierarchicalconfigurationdata.
• But…can'tbeloadedviathe@PropertySource.
20
my:servers:
- dev.bar.com- foo.bar.com
my.servers[0]=dev.bar.commy.servers[1]=foo.bar.com
YAML
JavaProperties
ExecutableJAR
• $ mvn package• Buildandpackagetheproject.• SpringBootwillrepackageitintoanexecutableone.
• $ java -jar target/\inception-0.0.1-SNAPSHOT.jar• It’sjustrunning.• Thejariscompletelyself-contained,youcandeployandrunitanywhere(withJava).
21
QuickStart
• SpringInitializrWebService• http://start.spring.io
• SpringSource ToolsSuite(eclipse-based)• https://spring.io/tools/sts/all
• IntelliJIDEAUltimate(Costs$$$)• https://www.jetbrains.com/idea/• OrimportSpringInitializr generatedprojectfromIntelliJIDEACommunityEdition.
23
DeveloperTools
• Setdevproperties,likedisablingcache.• Automaticrestart whenresourceschanged.• LiveReload thebrowser.• Remoteupdateanddebug.
24
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional>
</dependency>
ExternalizedConfiguration
1. Commandlinearguments.2. Propertiesfrom SPRING_APPLICATION_JSON.3. JNDIattributesfrom java:comp/env.4. JavaSystemproperties(System.getProperties()).5. OSenvironmentvariables.6. RandomValuePropertySource forrandom.*.7. Applicationpropertyfiles.8. @PropertySource [email protected]. SpringApplication.setDefaultProperties().
25
ApplicationPropertyFilesLookup
• ProfileandFileTypePriority1. application-{profile|default}.properties/.yml /.yaml2. application.properties/.yml /.yaml
• LocationPriority1. A/config subdirectoryofthecurrentdirectory.2. Thecurrentdirectory.3. Aclasspath /config package.4. Theclasspath root.
26
PropertyNameRelaxedBinding
Property Noteperson.firstName Standardcamelcasesyntax.person.first-name Dashednotation,recommended
forusein.propertiesand.yml files.person.first_name Underscorenotation,alternative
formatforusein.propertiesand.yml files.
PERSON_FIRST_NAME Uppercaseformat.Recommendedwhenusingasystemenvironmentvariables.
27
@ConfigurationProperties
• ItisType-safe.• Moreclearandexpressivethan@Value("{connection.username}")
28
@lombok.Data@Component@ConfigurationProperties(prefix = "connection")public class ConnectionProperties {
private String username = "anonymous";@NotNullprivate InetAddress remoteAddress;
}
IncorporateOur@Configurations
29
@Configuration@EnableAutoConfiguration@ComponentScanpublic @interface SpringBootApplication {
...}
@Order(Ordered.LOWEST_PRECEDENCE - 1)public class EnableAutoConfigurationImportSelectorimplements DeferredImportSelector...
ConfigurationOverrideConvention• Alwayslookupthepropertieslistfirst• http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
• Write@Configurationsand@Beansifneeded• Then@ComponentScan themin.• That’swhatyouarereallygoodat.
• AutoConfigurations justservesasafallback.
30
SpringBootActuator
“Anactuatorisamanufacturingterm,referringtoamechanicaldeviceformovingorcontrollingsomething.Actuatorscangeneratealargeamountofmotionfromasmallchange.”
32
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Production-ReadyEndpoints
• SpringConfiguration• autoconfig,beans,configprops,env andmappings
• Logging&stats• logfile,metrics,trace
• Informational• dump,info,flyway,liquibase
• Operational• shutdown
33
HealthInformation
• BeansimplementsHealthIndicator• Youcan@Autowired whatyouneedforhealthchecking.• Resultwillbecachedfor1secondsbydefault.
• Out-of-the-boxindicators• Application,DiskSpace,DataSource,Mail,Redis,Elasticsearch,Jms,Cassandra,Mongo,Rabbit,Solr…
34
Metrics
• Gauge• recordsasinglevalue.
• Counter• recordsadelta(anincrementordecrement).
• PublicMetrics• Exposemetricsthatcannotberecordviaoneofthosetwomechanisms.
35
AutoConfiguration
• META-INF/spring.factories
• Nothingspecialbut@Configuration.• SpringBootwillthenevaluateallAutoConfigurationavailablewhenbootstrapping.
37
# Auto Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.cht.inception.autoconfigure.DemoAutoConfiguration
@ConditionalOn*
• Eliminatingall@Configurationwillnotwork.• Knowingandusingbuilt-inswherepossible• @ConditionalOnBean• @ConditionalOnClass• @ConditionalOnMissingBean• @ConditionalOnMissingClass• @ConditionalOnProperty• …andmore
38
@Order matters
• HintsforSpringBoot• @AutoConfigureAfter• @AutoConfigureBefore
• Youstillhavetoknowwhatunderlying• Noteveryoperationisidempotentorcumulative.• WebSecurityConfigurerAdapter forexample.
39
@ConfigurationProperties
• Naming thingsseriously• There are only two hard things in Computer Science:
cache invalidation and naming things. -- Phil Karlton• Itwillbeanimportantpartofyourownframework!
• Generatespropertiesmetadataatcompiletime• LocatedatMETA-INF/spring-configuration-metedata.json.• ASpringBoot-awareIDEwillbegreathelpforyou.
40
PackageasWAR
• POM.xml• <packaging>war</packaging>
42
@SpringBootApplicationpublic class Application
extends SpringBootServletInitializerimplements WebApplicationInitializer {
...}
JBoss EAP
• JBoss EAPv6.0– 6.2• Havetoremoveembeddedserver.
• JBoss EAPv6.x• spring.jmx.enabled=false• server.servlet-path=/*
• http://stackoverflow.com/a/1939642• Multipartrequestcharsetencodingvalueiswrong.• HavetodowngradeJPAandHibernate.
• JBoss EAPv7• Haven’ttriedyet.
43
OracleWebLogicServer
• WebLogic11gandbelow• Notsupported.
• WebLogic12c• FilterregistrationlogicisWRONG!
• https://github.com/spring-projects/spring-boot/issues/2862#issuecomment-99461807
• Havetoremoveembeddedserver.• HavetodowngradeJPAandHibernate.• Havetospecify<wls:prefer-application-packages/> inweblogic.xml.
44