Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Environment agnostic applications with Spring

Environment agnostic applications with Spring

Slides from Szczecin Java User Group meetup that took place on the 17th of December 2014.

Story about building multienvironment applications, starting from Maven profiles, through simple property placeholder based solutions, Spring @Profiles and in the end Spring @Conditionals and Spring Boot

Maciej Walkowiak

December 17, 2014
Tweet

More Decks by Maciej Walkowiak

Other Decks in Programming

Transcript

  1. " " " DEV TEST PROD How to write application

    for multiple different environments?
  2. • Tell application how to behave when you run it,

    not when you build it. • No environment specific configuration in build time.
 Build as simple as: Configure in runtime mvn package
  3. • Each environment has it’s own properties file on classpath


    
 • Picked from environmental variable Simple solutions often work <context:property-placeholder location="classpath:application-${env}.properties"/> -Denv=dev
  4. • Since Spring 3.1 (December 2011) • Profiles tag group

    of beans into sets
 
 
 
 • There can be multiple profiles enabled at once • Activated by environmental variable Spring @Profiles -Dspring.profiles.active=dev & & & “dev” “test” “prod”
  5. Spring 4 @Conditionals • Conditionally creates bean • @ConditionalOnExpression! •

    @ConditionalOnProperty! • @ConditionalOnClass! • @ConditionalOnWebApplication! • …! • “@YourCustomConditional”! • @Profile is just a @Conditional specialisation Spring Boot
  6. Spring 4 @Conditionals # one of: filesystem,s3,mongo
 storage=filesystem @ConditionalOnProperty(name =

    "storage", havingValue = "s3")
 class S3StorageService implements StorageService {
 }
 
 @ConditionalOnProperty(name = "storage", havingValue = "mongo")
 class MongoStorageService implements StorageService {
 }
 
 @ConditionalOnProperty(name = "storage", havingValue = "filesystem", matchIfMissing = true)
 class FileSystemStorageService implements StorageService {
 }
  7. Spring Boot • Automatically picks up right application-${profile}.properties ! •

    YAML format support • Properties loading hierarchy Spring Boot
  8. • make build process as simple as possible • externalize

    application configuration • externalize logging configuration • provide defaults! • use Spring Boot Build once run everywhere