Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

Spring Boot

3.276 Aufrufe

Veröffentlicht am

Spring Boot basics, adopting and extending practices.

Veröffentlicht in: Technologie
  • Follow the link, new dating source: ♥♥♥ http://bit.ly/2F90ZZC ♥♥♥
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • Dating direct: ♥♥♥ http://bit.ly/2F90ZZC ♥♥♥
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier

Spring Boot

  1. 1. Spring Boot
  2. 2. Who Am I? • You will find me here https://github.com/tan9 http://stackoverflow.com/users/3440376/tan9 • My Java experience • Java and Java EE development – 8+ years • Spring Framework – 6+ years • Spring Boot – 1.5 years 2
  3. 3. Before We Get Started… • Join the channel: http://bit.do/spring-boot • Direct link: https://gitter.im/tan9/spring-boot-training • Sign in using your GitHub account • Or sign up right now! 3
  4. 4. Spring Framework 4
  5. 5. Spring Framework • Inversion of Control (IoC) container • Dependency Injection (DI) • Bean lifecycle management • Aspect-Oriented Programming (AOP) • “Plumbing” of enterprise features • MVC w/ RESTful, TX, JDBC, JPA, JMS… • Neutral • Does not impose any specific programming model. • Supports various third-party libraries. 5
  6. 6. Spring 2.5 JavaConfig • Favor Java Annotation (introduced in Java SE 5) • @Controller, @Service and @Repository • @Autowired • Thin XML configuration file 6 <context:annotation-config/> <context:component-scan base-package="com.cht"/>
  7. 7. JavaConfig Keep Evolving • @Bean & @Configuration since 3.0 • Get rid of XML configuration files. • @ComponentScan, @Enable* and @Profile since 3.1 • With WebApplicationInitializer powered by Servlet 3, say goodbye to web.xml too. • @Conditional since 4.0 • We’re able to filter beans programmatically. 7
  8. 8. Maven Bill-Of-Materials (BOM) • Keep library versions in ONE place. • Import from POM’s <dependencyManagement> section. • Declare dependencies without <version>: 8 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency>
  9. 9. Things Getting Complicated • Spring seldom deprecates anything • And offers little opinion or guidance. • Older approaches remain at the top in search results. • Bootstrapping can be painful • Due to the sheer size and growth rate of the portfolio. • Spring is an incredibly powerful tool… • Once you get it setup. Should you use spring boot in your next project? - Steve Perkins https://steveperkins.com/use-spring-boot-next-project/ 9
  10. 10. Spring Boot 10
  11. 11. ThoughtWorks Technology Radar 11 ThoughtWorks Techonlogy Rader April ‘16 https://www.thoughtworks.com/radar
  12. 12. Spring Boot • Opinionated • Convention over configuration. • Production-ready non-functional features • Embedded servers, security, metrics, health checks… • Speed up • Designed to get you up and running as quickly as possible. • Plain Java • No code generation and no XML configuration. 12
  13. 13. System Requirements • Spring Boot 1.3 requires Java 7+ by default • Java 8 is recommended if at all possible. • Can use with Java 6 with some additional configuration. • Servlet 3.0+ container • Embedded Tomcat 7+, Jetty 8+, Undertow 1.1+. • Oracle WebLogic Server 12c or later. • IBM WebSphere Application Server 8.5 or later. • JBoss EAP 6 or later. 13
  14. 14. Boot With Apache Maven 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>
  15. 15. Starter POMs • Make easy to add jars to your classpath. • spring-boot-starter-parent • Provides useful Maven defaults. • Defines version tags for “blessed” dependencies. • spring-boot-starter-* • Provides dependencies you are likely to need for *. 15
  16. 16. First Class package com.cht.inception; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.web.bind.annotation.*; @RestController @EnableAutoConfiguration public class Application { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 16
  17. 17. 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 2016-07-03 23:38:04.685 INFO 93490 --- [ main] com.cht.inception.Application : No active profile set, 2016-07-03 23:38:04.718 INFO 93490 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springfra 2016-07-03 23:38:05.482 INFO 93490 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with 2016-07-03 23:38:05.491 INFO 93490 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2016-07-03 23:38:05.491 INFO 93490 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine 2016-07-03 23:38:05.548 INFO 93490 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring emb 2016-07-03 23:38:05.548 INFO 93490 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationConte 2016-07-03 23:38:05.702 INFO 93490 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispa 2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'charac 2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hidden 2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPu 2016-07-03 23:38:05.705 INFO 93490 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'reques 2016-07-03 23:38:05.833 INFO 93490 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerA 2016-07-03 23:38:05.876 INFO 93490 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto jav 2016-07-03 23:38:05.879 INFO 93490 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" ont 2016-07-03 23:38:05.879 INFO 93490 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produc 2016-07-03 23:38:05.898 INFO 93490 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webja 2016-07-03 23:38:05.898 INFO 93490 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] o 2016-07-03 23:38:05.921 INFO 93490 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/fa 2016-07-03 23:38:05.986 INFO 93490 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for J 2016-07-03 23:38:06.032 INFO 93490 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port( 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)
  18. 18. 18
  19. 19. Application Properties • Place application.yaml in classpath • For example: • Configuring embedded server can be as easy as: 19 server: address: 127.0.0.1 port: 5566
  20. 20. YAML (YAML Ain’t Markup Language) • Superset of JSON. • UTF-8! • Really good for hierarchical configuration data. • But… can't be loaded via the @PropertySource. 20 my: servers: - dev.bar.com - foo.bar.com my.servers[0]=dev.bar.com my.servers[1]=foo.bar.com YAML Java Properties
  21. 21. Executable JAR • $ mvn package • Build and package the project. • Spring Boot will repackage it into an executable one. • $ java -jar target/ inception-0.0.1-SNAPSHOT.jar • It’s just running. • The jar is completely self-contained, you can deploy and run it anywhere (with Java). 21
  22. 22. Spring Boot: Dev 22
  23. 23. Quick Start • Spring Initializr Web Service • http://start.spring.io • SpringSourceTools Suite (eclipse-based) • https://spring.io/tools/sts/all • IntelliJ IDEA Ultimate (Costs $$$) • https://www.jetbrains.com/idea/ • Or import Spring Initializr generated project from IntelliJ IDEA Community Edition. 23
  24. 24. Developer Tools • Set dev properties, like disabling cache. • Automatic restart when resources changed. • LiveReload the browser. • Remote update and debug. 24 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
  25. 25. Externalized Configuration 1. Command line arguments. 2. Properties from SPRING_APPLICATION_JSON. 3. JNDI attributes from java:comp/env. 4. Java System properties (System.getProperties()). 5. OS environment variables. 6. RandomValuePropertySource for random.*. 7. Application property files. 8. @PropertySource on @Configuration. 9. SpringApplication.setDefaultProperties(). 25
  26. 26. Application Property Files Lookup • Profile and File Type Priority 1. application-{profile|default}.properties / .yml / .yaml 2. application.properties/ .yml / .yaml • Location Priority 1. A /config subdirectory of the current directory. 2. The current directory. 3. A classpath /config package. 4. The classpath root. 26
  27. 27. Property Name Relaxed Binding Property Note person.firstName Standard camel case syntax. person.first-name Dashed notation, recommended for use in .properties and .yml files. person.first_name Underscore notation, alternative format for use in .properties and .yml files. PERSON_FIRST_NAME Upper case format. Recommended when using a system environment variables. 27
  28. 28. @ConfigurationProperties • It is Type-safe. • More clear and expressive than @Value("{connection.username}") 28 @lombok.Data @Component @ConfigurationProperties(prefix = "connection") public class ConnectionProperties { private String username = "anonymous"; @NotNull private InetAddress remoteAddress; }
  29. 29. Incorporate Our @Configurations 29 @Configuration @EnableAutoConfiguration @ComponentScan public @interface SpringBootApplication { ... } @Order(Ordered.LOWEST_PRECEDENCE - 1) public class EnableAutoConfigurationImportSelector implements DeferredImportSelector...
  30. 30. Configuration Override Convention • Always look up the properties list first • http://docs.spring.io/spring- boot/docs/current/reference/html/common- application-properties.html • Write @Configurations and @Beans if needed • Then @ComponentScan them in. • That’s what you are really good at. • AutoConfigurations just serves as a fallback. 30
  31. 31. Spring Boot: Run 31
  32. 32. Spring Boot Actuator “An actuator is a manufacturing term, referring to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change.” 32 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
  33. 33. Production-Ready Endpoints • Spring Configuration • autoconfig, beans, configprops, env and mappings • Logging & stats • logfile, metrics, trace • Informational • dump, info, flyway, liquibase • Operational • shutdown 33
  34. 34. Health Information • Beans implements HealthIndicator • You can @Autowired what you need for health checking. • Result will be cached for 1 seconds by default. • Out-of-the-box indicators • Application, DiskSpace, DataSource, Mail, Redis, Elasticsearch, Jms, Cassandra, Mongo, Rabbit, Solr… 34
  35. 35. Metrics • Gauge • records a single value. • Counter • records a delta (an increment or decrement). • PublicMetrics • Expose metrics that cannot be record via one of those two mechanisms. 35
  36. 36. Spring Boot: Ext Custom AutoConfigurationsand ConfigurtaionProperties 36
  37. 37. Auto Configuration • META-INF/spring.factories • Nothing special but @Configuration. • Spring Boot will then evaluate all AutoConfiguration available when bootstrapping. 37 # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.cht.inception.autoconfigure.DemoAutoConfiguration
  38. 38. @ConditionalOn* • Eliminating all @Configuration will not work. • Knowing and using built-ins where possible • @ConditionalOnBean • @ConditionalOnClass • @ConditionalOnMissingBean • @ConditionalOnMissingClass • @ConditionalOnProperty • … and more 38
  39. 39. @Order matters • Hints for Spring Boot • @AutoConfigureAfter • @AutoConfigureBefore • You still have to know what underlying • Not every operation is idempotent or cumulative. • WebSecurityConfigurerAdapter for example. 39
  40. 40. @ConfigurationProperties • Naming things seriously • There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton • It will be an important part of your own framework! • Generates properties metadata at compile time • Located at META-INF/spring-configuration- metedata.json. • A Spring Boot-aware IDE will be great help for you. 40
  41. 41. Deploying 41
  42. 42. Package as WAR • POM.xml • <packaging>war</packaging> 42 @SpringBootApplication public class Application extends SpringBootServletInitializer implements WebApplicationInitializer { ... }
  43. 43. JBoss EAP • JBoss EAP v6.0 – 6.2 • Have to remove embedded server. • JBoss EAP v6.x • spring.jmx.enabled=false • server.servlet-path=/* • http://stackoverflow.com/a/1939642 • Multipart request charset encoding value is wrong. • Have to downgrade JPA and Hibernate. • JBoss EAP v7 • Haven’t tried yet. 43
  44. 44. Oracle WebLogic Server • WebLogic 11g and below • Not supported. • WebLogic 12c • Filter registration logic is WRONG! • https://github.com/spring-projects/spring- boot/issues/2862#issuecomment-99461807 • Have to remove embedded server. • Have to downgrade JPA and Hibernate. • Have to specify <wls:prefer-application- packages/> in weblogic.xml. 44
  45. 45. IBM WebSphere AS • WebSphere AS v8.5.5 • Have to remove embedded server. • Have to downgrade JPA and Hibernate. 45
  46. 46. What’s Next? 46
  47. 47. Try JHipster https://jhipster.github.io/ and to learn something from him. 47
  48. 48. References • Introduction to Spring Boot - Dave Syer, Phil Webb • http://presos.dsyer.com/decks/spring-boot-intro.html • Spring Boot Reference Guide • http://docs.spring.io/spring-boot/docs/current/ 48

×