Configuration Enhancements in Spring 3.1

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

21874091836ab7d3a769c1a89a0702f3?s=128

Chris Beams

October 22, 2010
Tweet

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 2.x <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="..."> <context:component-scan base-package="com.bank"/>

    </beans> 6
  7. Configuration in Spring 3.0 @Configuration class Config { @Bean public

    MyService myService() { return new MyService(myRepository()); } } 7
  8. 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
  9. 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
  10. 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 { }
  11. 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
  12. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Spring AMQP @Configuration use
  13. 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
  14. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 On to Spring 3.1 ...
  15. 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
  16. SpringOne 2GX 2009. All rights reserved. Do not distribute without

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

    your application needs to work and their configuration - Jez Humble, Continuous Delivery
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. Major Components • Environment interface and implementations • PropertySource abstraction

    • EnvironmentAware interface • EnvironmentAwarePropertyPlaceholderConfigurer – integrated <context:property-placeholder/> • EnvironmentAwarePropertyOverrideConfigurer • SpEL support • ProfileResolver 23
  24. 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
  25. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Bean Definition Profiles
  26. 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
  27. 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 { ... }
  28. Profile activation • java -DspringProfiles="p1,p2" ... • <context-param>, <init-param> •

    ConfigurableEnvironment.setActiveProfiles("p1", "p2") 28
  29. 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>
  30. 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
  31. 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
  32. Testing support • MockEnvironment • MockPropertySource • Easily mock out

    system props environment vars 32
  33. 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
  34. 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
  35. What remains to be done • Tooling support in STS

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

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

    permission. Chicago, October 19 - 22, 2010 c: namespace
  38. 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
  39. SpringOne 2GX 2009. All rights reserved. Do not distribute without

    permission. Chicago, October 19 - 22, 2010 Java-Based App Config
  40. 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
  41. 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
  42. Declarative XML == Declarative Java • Think about – <context:component-scan

    base-package="..."/> • No method references • No bean references • Annotations are a natural fit • @ComponentScan! 42
  43. @ComponentScan • Originally appeared in JavaConfig milestones 43

  44. 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
  45. 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
  46. Other Items • TestContext support for @Configuration 46

  47. 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
  48. 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
  49. SpringOne 2GX 2009. All rights reserved. Do not distribute without

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