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

Configuration Enhancements in Spring 3.1

cbeams
October 22, 2010

Configuration Enhancements in Spring 3.1

As presented at SpringOne/2GX 2010 in Chicago, IL.
- Video at http://www.infoq.com/presentations/Configuration-in-Spring-3-1

cbeams

October 22, 2010
Tweet

More Decks by cbeams

Other Decks in Programming

Transcript

  1. SpringOne 2GX 2010. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Configuration Enhancements in Spring 3.1 Chris Beams
  2. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Let's review: 10 years in 10 slides
  3. Configuration in Spring 1.x <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 1.0.2//EN"

    "http://www.springframework.org/dtd/spring-beans-1.0.2.dtd"> <beans> <bean id="transferService" class="com.bank.DefaultTransferService"> <property name="minimum" value="${amount.min}"/> </bean> <bean class="org.sfwk.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:transfer.properties"/> </bean> </beans> 3
  4. Configuration in Spring 2.x <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="..."> <bean id="transferService"

    class="com.bank.DefaultTransferService" p.minimum="${amount.min}"/> <bean class="org.sfwk.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:transfer.properties"/> </bean> </beans> 4
  5. Configuration in Spring 2.x <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="..."> <bean id="transferService"

    class="com.bank.DefaultTransferService" p.minimum="${amount.min}"/> <context:property-placeholder location="classpath:transfer.properties"/> </beans> 5
  6. Configuration in Spring 3.0 @Configuration class Config { @Bean public

    MyService myService() { return new MyService(myRepository()); } } 7
  7. Configuration Recap • Spring 1.x – Configuration using <beans/> XML

    • Spring 2.0 – Configuration with high-level XML namespaces • Spring 2.5 – Annotation-Driven Injection with @Autowired – Support for JSR-250 @PostConstruct, et al • Spring 3.0 – Code-based config with @Configuration – Support for JSR-330 @Inject standard annotations – Rounded out annotation support 8
  8. Notice a Pattern? • From release to release – Incrementally

    improve existing config functionality – Every so often, introduce truly new features – Start minimal, let the feature prove itself, iterate – Evolution, not revolution 9
  9. Since 3.0... • XML continues to be very widely used

    – It's not going anywhere • @Autowired and component scanning also enjoy wide use – Especially in web tier with @Controller, etc – Stereotype annotations could be used more widely • @Service, @Repository, ... – Custom annotations and using Spring's support for meta- annotations could be used more widely 10 @Transactional @Service @Retention(RUNTIME) @interface MyService { }
  10. Since 3.0: @Configuration adoption • Case study: spring-amqp – Zero

    XML configuration in src/main – Exposes abstract @Configuration classes as a type-safe contract for configuring Spring applications against RabbitMQ. – Leads to a natural, object-oriented style of dependency injection 11
  11. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Spring AMQP @Configuration use
  12. Since 3.0: JSR-330 adoption • Spring • JSR-299 (CDI) sits

    atop JSR-330 – So any JEE 6 server provides support out of the box – Candi (Resin) – Or standalone implementations may be used • Weld • OpenWebBeans • Guice – JSR-330 "supported but discouraged" • Available only in Guice SVN • http://code.google.com/p/google-guice/wiki/JSR330 • http://stackoverflow.com/questions/1884437/jsr-330-and-guice- interoperability 13
  13. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 On to Spring 3.1 ...
  14. Configuration Themes in Spring 3.1 • Environment support – Unified

    property management – Bean definition profiles • Nested <beans/> elements • c: namespace • Feature-parity between @Configuration classes and XML namespaces • Groovy/Grails BeanBuilder integration 15
  15. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Environment support
  16. Environment 17 An environment is all of the resources that

    your application needs to work and their configuration - Jez Humble, Continuous Delivery
  17. Support that's been a long time coming • Consistently popular

    request from community and customers • Specifics vary, but there are common use cases and themes – Promote a single binary through the deployment pipeline of dev -> qa -> staging -> prod. – Smarter support for properties, including hierarchical access, avoiding duplication, etc. • Just search JIRA for 'property' or 'environment' to get a taste. 18
  18. Making it First-Class • Users have been able to meet

    most any environment- related need one way or another with Spring, using imports, property placeholders, etc. • But it's time to make things first class. • Let's take a look at the 'machinery' of Spring 3.1's Environment as it stands today. 19
  19. Environment interface • Integrated throughout the core DI container –

    ApplicationContext implementations – WebApplicationContext implementations – Bean definition readers and scanners • Provides a single access point for properties – Environment.getProperty(String) • As well as various conveniences – Environment.getProperty(String, Class<?>) – Environment.getRequiredProperty(String) 20
  20. PropertySource • Under the hood, an Environment aggregates PropertySource objects

    • Implementations for Map, Properties, ServletContext, etc – e.g., DefaultEnvironment registers one for system properties, one for environment variables • The Environment's collection of PropertySources is yours to manipulate at container bootstrap time 21
  21. Properties are Everywhere • Properties files on filesystem or classpath

    • System environment • System properties • LDAP / JNDI • ServletContext / ServletConfig params • Any Map or Property object instance • Each can be represented by a PropertySource and registered with the Environment 22
  22. Major Components • Environment interface and implementations • PropertySource abstraction

    • EnvironmentAware interface • EnvironmentAwarePropertyPlaceholderConfigurer – integrated <context:property-placeholder/> • EnvironmentAwarePropertyOverrideConfigurer • SpEL support • ProfileResolver 23
  23. SpEL Support • The context's Environment instance is registered as

    a singleton with the container, so can be accessed like any other bean. • #{environment['prop.key']} – translates to: Environment.getProperty("prop.key"); 24
  24. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Bean Definition Profiles
  25. What is a bean definition profile? • A group of

    bean definitions to be registered conditionally • Not just about dev->qa->prod • Could also be used to support – Customer A vs. Customer B deployment scenarios – Deploying to different production target platforms (WLS vs JBoss, etc) – Ad-hoc 'switching on' of JMX or other instrumentation 26
  26. Profile demarcation 27 <beans profile="development"> <bean id="dataSource" class="..."/> </beans> @Profile("development")

    @Component public class MyComponent { ... } @Profile("development") @Configuration public class MyConfig { @Bean public TransferService transferService() { ... } } @Profile("development") @Component @Retention(RUNTIME) public @interface DevComponent { ... }
  27. Nested <beans> • First devised as a convenience feature for

    profiles 29 • But useful in general as a grouping mechanism for beans with similar defaults <beans> <bean id="notLazy" class="..."/> <beans default-lazy-init="true"> <bean id="lazy1" class="..."/> <bean id="lazy2" class="..."/> </beans> </beans> <beans> <bean id="always" class="..."/> <beans profile="perf"> <bean id="performanceAspect" class="..."/> </beans> </beans>
  28. Nested <beans>: Design decisions • Avoid any kind of explicit

    'conditional' constructs in XML • Always been able to defend Spring's XML syntax – not "programming in xml" • Avoid mistakes of Ant, Jelly, etc • Nested <beans> elements may occur only at the bottom of the file – To help mitigate any potential noise 30
  29. Nested <beans>: Implications • In order to support this cleanly,

    all use of xsd:ID types has been removed from the core schemas • Allows for duplicating a bean id across nesting levels • Container still raises an error if a bean is duplicated within the same nesting level 31
  30. Potential profile pitfalls • False confidence in testing process –

    If different bean definitions are loaded in production as opposed to testing, QA didn't really test an accurate configuration • Security vs. Convenience tradeoff – It's convenient 33
  31. Profile tips • As a rule, bean topology shouldn't be

    changing across test and production environments - only simple properties. • Creating a secure build probably involves efforts at the build system level • Don't include dev-only (or otherwise insecure) jars and profiles in the build to be promoted through testing and ultimately to production 34
  32. What remains to be done • Tooling support in STS

    – Visualizing active vs. inactive profiles – Recognizing nested <beans> elements 35
  33. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Profile Demo
  34. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 c: namespace
  35. c(onstructor): namespace • Convenient syntax for configuring constructor argument parameters

    in XML • Rounds out the support introduced by the p: namespace in Spring 2.0 • <bean class="..." c:dataSource="dataSource" /> 38
  36. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Java-Based App Config
  37. Completing the @Configuration vision • Spring 3.0 mapped <bean/> to

    @Bean • Straightforward, but: – Doesn't handle the rest of application configuration – What about <context:component-scan/>, etc? 40
  38. Challenges • Mapping spring namespaces into code isn't entirely straightforward

    • 3 'types' of Spring namespace elements – Purely declarative • <context:component-scan/> – References beans and/or methods • <tx:annotation-driven/> – Full-blown "DSLs in XML" • Spring Integration • Spring Batch • Spring Web Flow 41
  39. Declarative XML == Declarative Java • Think about – <context:component-scan

    base-package="..."/> • No method references • No bean references • Annotations are a natural fit • @ComponentScan! 42
  40. Builder-style APIs • Prime directive in code-based config – No

    string identifiers! • Think about – <tx:annotation-driven transactionManager="txManager"/> – Has to be a string in XML, should be a typesafe reference in Java – Therefore, annotations are no good – e.g.: • @AnnotationDrivenTx(transactionManager="txManager") • annotationDrivenTx().withTransactionManager(txManager ()) 44
  41. XML DSLs • Example: Spring Web Flow – Rich 'domain

    specific language' for stateful web applications – No automatic way to translate into code – Requires careful design by the Web Flow team – @Flow definitions are here with Web Flow 3.0 45
  42. Spring 3.1 will... • Improve incrementally – Greater convenience in

    XML with c: namespace • Introduce first-class environment support – Unified property access via the Spring Environment – Bean definition profile support with @Profile and 'profile' XML attribute • Translate XML namespaces into code – Where it makes sense • Provide deeper support for Groovy – Integrating the BeanBuilder API into core 47
  43. Give it a try • http://git.springsource.org/sandbox/cbeams.git • Will be merged

    into the usual Spring SVN repository shortly • In the meantime, 3.1.0 snapshots containing (just about) everything you've seen here are already available – http://maven.springframework.org/snapshots • Feedback, please! 48
  44. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Q&A