SlideShare ist ein Scribd-Unternehmen logo
1 von 72
Downloaden Sie, um offline zu lesen
DI Styles: Choosing the Right Tool for the Job

Chris Beams, Senior Technical Staff, SpringSource




                                                                                 CONFIDENTIAL

                                                    Š 2010 SpringSource, A division of VMware. All rights reserved
Hello!

 Chris Beams
 • Senior Staff Engineer with SpringSource
 • Member Core Spring team
 • Trained hundreds to use Spring effectively
 • Author of the forthcoming Spring in a Nutshell (O'Reilly)




                                      CONFIDENTIAL             2
Dependency Injection: Simple, Right?




     TransferService                           AccountRepository

     public TransferService(AccountRepository ar) {
         this.accountRepository = ar;
     }




                                CONFIDENTIAL                       3
Choices




                                              @Configuration
       @Autowired

    <context:annotation-config/>
                                                       @Bean
    <context:component-scan/>       @Inject


                       @Component

                                                    @Configurable
                <bean/>
                                        ...




                                   CONFIDENTIAL                     4
Agenda
 A brief history of Dependency Injection (DI)
 Seven characteristics of a DI style
 A demo-centric tour of Spring DI styles
 • Comparative analysis of available styles
 • What's new in Spring 3 for DI
 • Demo sources available at:
   • http://github.com/cbeams/distyles




                                         CONFIDENTIAL   5
Agenda
 A brief history of Dependency Injection (DI)
 Seven characteristics of a DI style
 A demo-centric tour of Spring DI styles
 • Comparative analysis of available styles
 • What's new in Spring 3 for DI
 • Demo sources available at:
   • https://src.springsource.org/svn/springone2gx/distyles




                                         CONFIDENTIAL         6
Agenda
 A brief history of Dependency Injection (DI)
 Seven characteristics of a DI style
 A demo-centric tour of Spring DI styles
 • Comparative analysis of available styles
 • What's new in Spring 3 for DI
 • Demo sources available online
   • http://github.org/cbeams/distyles




                                         CONFIDENTIAL   7
A one-slide history of DI

 2000: Fowler, et al coin 'POJO'
 2002: Johnson, et al: 1:1 J2EE; J2EE w/o EJB
 2002-3: Spring and other 'lightweight IoC containers' emerge
 2004: Fowler coins 'Dependency Injection as a specialization of the
  Inversion of Control principle'
  • Defined three 'types' of DI
    • Constructor Injection
    • Setter Injection
    • Interface Injection
 2004-present: Spring evolves; DI is widely adopted




                                    CONFIDENTIAL                    8
DI: Why?

 Dependency Injection enables 'POJO programming'
 POJO programming facilitates
  • Simplicity
  • Effective separation of concerns
  • Proper unit testing
 Well-factored and well-tested code
  • Tends to be well-designed code
  • Evolves well into maintainable systems




                                  CONFIDENTIAL      9
DI: Where to Inject?

 Three possible 'Injection Points'
  • Constructor
    • Good for mandatory dependencies
  • Setter
    • Good for optional dependencies
  • Field
    • Good for injecting system test fixtures in JUnit tests




                                    CONFIDENTIAL               10
DI: How to Configure?

 Styles for expressing DI metadata and instructions
  • External
     • Configuration files (XML, properties, ...)
     • Code (Java)
     • DSL (Spring XML namespaces, Groovy, ...)
  • Internal
     • Annotations embedded within POJOs
     • Usually requires at least some external configuration




                                   CONFIDENTIAL                11
DI: Evolution

 We've come a long way since Fowler coined DI
 Today developers are faced with many choices
  • Annotations changed the game
  • Rise of non-Java languages on the JVM creates new possibilities




                                 CONFIDENTIAL                         12
DI: Today's Choices

 Open-source projects
  • Spring
  • Grails BeanBuilder
  • Google Guice
  • Many other projects across languages
 Standards efforts
  • JSR-250 (Common Annotations)
  • JSR-299 (Java Contexts and Dependency Injection)
  • JSR-330 (Dependency Injection for Java)
  • OSGi 4.2 Blueprint Container




                                CONFIDENTIAL           13
Choosing a DI Style




       CONFIDENTIAL   14
DI Configuration: What matters to you?

 Let's begin by defining the characteristics that matter when thinking
 about DI
 Provide a framework for making decisions about your own
 applications




                                CONFIDENTIAL                         15
Seven Characteristics of a DI Style

1.External vs. Internal
2.Explicit vs. Implicit
3.Type-safety
4.Noninvasiveness
5.Portability (of POJOs)
6.Configurability of 3rd party components
7.Tooling support




                               CONFIDENTIAL   16
Characteristic 1: External vs. Internal


                           External
 <bean id=“transferService” class=“com.bank.TransferServiceImpl”>
   <constructor-arg ref=“accountRepository” />
 </bean>

                           Internal

 @Component
 public class TransferServiceImpl implements TransferService {
   @Autowired
   public TransferServiceImpl(AccountRepository repo) {
     this.accountRepository = repo;
   }
   …
 }



                               CONFIDENTIAL                      17
Characteristic 1: External vs. Internal

 External DI is noninvasive
  • But causes context-switching during coding
  • More verbose
  • Provides a 'blueprint' of your application
 Internal DI is necessarily invasive
  • May or may not be portable
  • But requires less coding and maintenance
  • Easier to use during development




                                  CONFIDENTIAL   18
Seven Characteristics of a DI Style

1.External vs. Internal
2.Explicit vs. Implicit
3.Type-safety
4.Noninvasiveness
5.Portability (of POJOs)
6.Configurability of 3rd party components
7.Tooling support




                               CONFIDENTIAL   19
Characteristic 2: Explicit vs. Implicit


<bean id=“transferService” class=“com.bank.TransferServiceImpl”>
  <constructor-arg ref=“accountRepository” />
  <constructor-arg ref=“feePolicy” />
</bean>

<bean id=“accountRepository” class=“com.bank.JdbcAccountRepository”>
<bean id=“feePolicy” class=“com.bank.FlatFeePolicy”>


public class TransferServiceImpl implements TransferService {

    public TransferServiceImpl(AccountRepository accountRepository,
                               FeePolicy feePolicy) {
      …
    }
    …
}



                                   CONFIDENTIAL                       20
Characteristic 2: Explicit vs. Implicit


<context:component-scan base-package=“com.bank">

@Component
public class TransferServiceImpl implements TransferService {
  @Autowired
  public TransferServiceImpl(AccountRepository accountRepository,
                             FeePolicy feePolicy) { … }
  …
}

@Component
public class JdbcAccountRepository implements AccountRepository{ … }

@Component
public class FlatFeePolicy implements FeePolicy{ … }




                                     CONFIDENTIAL                      21
Characteristic 2: Explicit vs. Implicit

 Explicit DI comes with greater verbosity
  • More tedious in simple cases
  • Easier and more clear when things get complicated
 Implicit DI introduces the possibility of ambiguity
  • If multiple implementations of a given type are detected / scanned
  • Disambiguation strategies are required
  • But ambiguities may arise at any time




                                   CONFIDENTIAL                          22
Explicit vs. Implicit: Ambiguity


<context:component-scan base-package=“com.bank">

@Component
public class TransferServiceImpl implements TransferService {
  @Autowired
  public TransferServiceImpl(AccountRepository accountRepository,
                             FeePolicy feePolicy) { … }
  …
}

@Component
public class JdbcAccountRepository implements AccountRepository{ … }

@Component
public class FlatFeePolicy implements FeePolicy{ … }                Which one
                                                                    should get
@Component
                                                                    injected?
public class VariableFeePolicy implements FeePolicy{ … }



                                     CONFIDENTIAL                                23
Implicit DI: Disambiguation


<context:component-scan base-package=“com.bank">

@Component
public class TransferServiceImpl implements TransferService {
  @Autowired
  public TransferServiceImpl(AccountRepository repo,
                             @Qualifer(“domestic”) FeePolicy feePolicy) { … }
  …
}

@Component
public class JdbcAccountRepository implements AccountRepository{ … }

@Component
@Qualifier(“domestic”)
public class FlatFeePolicy implements FeePolicy{ … }

@Component(“international”)
public class VariableFeePolicy implements FeePolicy{ … }




                                       CONFIDENTIAL                             24
Seven Characteristics of a DI Style

1.External vs. Internal
2.Explicit vs. Implicit
3.Type-safety
4.Noninvasiveness
5.Portability (of POJOs)
6.Configurability of 3rd party components
7.Tooling support




                               CONFIDENTIAL   25
Characteristic 3: Type-safety

 XML is inherently not type-safe
  • Tooling can mitigate this
    • STS/IDEA/NetBeans are Spring XML-aware and can raise warnings
     and errors at development time
 How can one get the compiler to catch errors in DI configuration?
  • Custom @Qualifier annotations
  • @Configuration classes




                                CONFIDENTIAL                          26
Seven Characteristics of a DI Style

1.External vs. Internal
2.Explicit vs. Implicit
3.Type-safety
4.Noninvasiveness
5.Portability (of POJOs)
6.Configurability of 3rd party components
7.Tooling support




                               CONFIDENTIAL   27
Characteristic 4: (Non)invasiveness

 Originally, noninvasiveness was a defining characteristic of DI and
  POJO programming
 Noninvasiveness matters because
  • An object should be usable independent of its environment and context
  • Especially important when it comes to testing
 But...
  • Annotations changed this




                                 CONFIDENTIAL                          28
Annotations and Invasiveness

 Annotations, by definition, are invasive
  • Requires modifying POJOs
 But we may say they are minimally invasive
  • Because annotations have no detrimental effect on the utility of a POJO
  • Java 6 even allows for annotations to be missing from the classpath at
   runtime
 Non-standard annotations still impact portability




                                  CONFIDENTIAL                           29
Seven Characteristics of a DI Style

1.External vs. Internal
2.Explicit vs. Implicit
3.Type-safety
4.Noninvasiveness
5.Portability (of POJOs)
6.Configurability of 3rd party components
7.Tooling support




                               CONFIDENTIAL   30
Characteristic 5: Portability

 Ideally, a POJO should be reusable across DI frameworks
 Non-standard annotations tie you to a particular framework
  • Hence the desire for standardization
  • JSR-330!




                                CONFIDENTIAL                   31
Seven Characteristics of a DI Style

1.External vs. Internal
2.Explicit vs. Implicit
3.Type-safety
4.Noninvasiveness
5.Portability (of POJOs)
6.Configurability of 3rd party components
7.Tooling support




                               CONFIDENTIAL   32
Characteristic 6: Configurability of 3rd Party Components

 Internal configuration and 3rd party components don't mix
  • You can't annotate somebody else's code
 External configuration is the only way
  • Hence a complete DI solution must support both




                               CONFIDENTIAL                   33
Seven Characteristics of a DI Style

1.External vs. Internal
2.Explicit vs. Implicit
3.Type-safety
4.Noninvasiveness
5.Portability (of POJOs)
6.Configurability of 3rd party components
7.Tooling support




                               CONFIDENTIAL   34
Characteristic 7: Tooling Support

 Natural, integrated refactoring
  • XML-driven DI requires Spring-aware tooling
  • Code-driven DI takes advantage of built-in IDE Java tooling
 Content Assist in configuration files
  • Generic XML tooling only gets you so far
  • Need XML tooling built to purpose
 Visualization
  • Seeing the 'blueprint' of your application
 Other concerns
  • Static analysis
  • Obfuscation




                                  CONFIDENTIAL                    35
SpringSource Tool Suite (STS)




                           CONFIDENTIAL   36
A Tour of DI Styles




       CONFIDENTIAL   37
DI Styles

 XML
  • <beans/>
  • <namespace:*/>
 @Autowired
 @Configuration
 Standards
  • JSR-250 (Common Annotations)
  • JSR-299 (Java Contexts and Dependency Injection)
  • JSR-330 (Dependency Injection for Java)




                                CONFIDENTIAL           38
DI Styles

 Remember...
  • DI styles need not be mutually exclusive!
  • You'll probably use more than one in a given app




                                  CONFIDENTIAL         39
<beans/>




  CONFIDENTIAL   40
<beans/> XML

 The original DI style for Spring
 Remains very widely used
 General-purpose, thus very powerful
 But can get verbose / maintenance-intensive




                                 CONFIDENTIAL   41
<beans/> demo




    CONFIDENTIAL   42
<beans/>: Summary

1.External vs. Internal: External
2.Explicit vs. Implicit: Explicit
3.Type-safe: No
4.Noninvasive: Yes
5.Portable: Yes
6.Can configure 3rd party components: Yes
7.Has tooling support: Yes




                                    CONFIDENTIAL   43
<namespace:*/>




     CONFIDENTIAL   44
<namespace:*/> XML

 Introduced in Spring 2.0
 Expanded in Spring 2.5 and 3.0
 Widely supported by Spring projects
  • Spring Integration
  • Spring Batch
  • Spring Web Flow
  • Spring Security
  • ...
 Greatly reduces XML verbosity
 More expressive at the same time




                               CONFIDENTIAL   45
<namespace:*/> demo




       CONFIDENTIAL   46
<namespace:*/>: Summary

 Same fundamental characteristics as <beans/>
 But eliminates much of the verbosity problem with XML
 • Serves as a 'configuration DSL'
 Not just about DI
 • Helps manage many other aspects of the application
 • Scheduling, AOP, security, etc.




                                     CONFIDENTIAL         47
@Autowired




   CONFIDENTIAL   48
@Autowired

 AKA "Annotation-driven injection"
 Introduced in Spring 2.5
 More annotations added in Spring 3.0
  • @Primary
  • @Lazy
  • @DependsOn
  • extended semantics for @Scope
 Widely used today
 Works in conjunction with @Component and <context:component-
 scan/> to streamline development lifecycle




                               CONFIDENTIAL                  49
@Autowired demo




     CONFIDENTIAL   50
@Autowired: Summary

1.External vs. Internal: Internal
2.Explicit vs. Implicit: Implicit
3.Type-safe: Yes
4.Noninvasive: No
5.Portable: No
6.Can configure 3rd party components: No
7.Has tooling support: Yes (as of STS 2.2.0)




                                    CONFIDENTIAL   51
JSR-330 (@Inject)




      CONFIDENTIAL   52
Introducing JSR-330

 AKA @Inject
 A joint JCP effort by Google and SpringSource
 Provides common understanding of injection semantics through
 portable DI annotations
 Packaged under javax.inject.* (Java SE)
 JSR went final late 2009
 • API is available in Maven Central
 Spring 3.0 GA passes the TCK




                                       CONFIDENTIAL              53
Smallest. JSR. Ever.




                       CONFIDENTIAL   54
JSR-330 demo




    CONFIDENTIAL   55
JSR-330: Summary

1.External vs. Internal: Internal
2.Explicit vs. Implicit: Undefined! (can be either)
3.Type-safe: Yes
4.Noninvasive: No
5.Portable: Yes
6.Can configure 3rd party components: No
7.Has tooling support: Yes (STS)




                                    CONFIDENTIAL      56
@Autowired and @Inject: The Bottom Line

 JSR-330 standardizes internal DI annotations
 • Meaning: portable POJOs
 However, @Inject is a subset of the functionality provided by
 Spring's @Autowired support
 Rule of thumb
 • You can get 80% of what you need with @Inject
 • Rely on @Autowired and friends for the rest




                                    CONFIDENTIAL                  57
From @Autowired to @Inject

Spring          javax.inject.*
@Autowired      @Inject *                       @Inject has no 'required' attribute


@Component      @Named *                        Spring supports scanning for @Named


@Scope          @Scope *                        for meta-annotation and injection points
                                                only

@Scope          @Singleton *                    jsr-330 default scope is like Spring's
                                                'prototype'
("singleton")

@Qualifier      @Qualifier, @Named
@Value          no equivalent                   see SPR-6251 for ideas on how Spring can
                                                help bridge this gap


@Primary        no equivalent
@Lazy           no equivalent
@Required       no equivalent

                                 CONFIDENTIAL                                            58
@Configuration




     CONFIDENTIAL   59
@Configuration

 Formely Spring JavaConfig
 Now included in core Spring Framework 3.0
 Annotation-driven, but is an external DI style
 • POJOs remain untouched by annotations
 Provides full programmatic control over object instantiation and DI
 Allows for object-oriented configuration
 Integrates well with other Spring DI styles




                                 CONFIDENTIAL                       60
A @Configuration class

  @Configuration
  public class AppCong {

      @Bean
      public TransferService transferService() {
        return new TransferService(accountRepository());
      }

      @Bean
      public AccountRepository accountRepository() {
        return new JdbcAccountRepository(dataSource());
      }

      // ...
  }



                               CONFIDENTIAL                61
Look familiar?



<bean id=“transferService” class=“com.bank.TransferServiceImpl”>
  <constructor-arg ref=“accountRepo” />
</bean>

<bean id=“accountRepo” class=“com.bank.JdbcAccountRepository”>
  <constructor-arg ref=“dataSource” />
</bean>




                              CONFIDENTIAL                     62
Bootstrapping @Configuration



 public class CommandLineApplication {

     public static void main(String... args) {
       ApplicationContext ctx =
          new AnnotationCongApplicationContext(AppCong.class);

         TransferService transferService = ctx.getBean(TransferService.class);

         transferService.transfer(100.00, “A123”, “C456”);
     }

 }




                                      CONFIDENTIAL                           63
@Configuration demo




       CONFIDENTIAL   64
@Configuration: Summary

1.External vs. Internal: External
2.Explicit vs. Implicit: Explicit
3.Type-safe: Yes
4.Noninvasive: Yes
5.Portable: Yes
6.Can configure 3rd party components: Yes
7.Has tooling support: Yes




                                    CONFIDENTIAL   65
Spring is about choice

 Choice in many areas...
 All DI metadata (internal or external) contributes to the core
  BeanDefinition model
 • This layer is what makes adding different configurations styles possible!
 Spring embraces any relevant deployment environment
 • Use latest DI/EE6 styles on
   • J2EE 1.5 and JEE 5
   • OSGi




                                      CONFIDENTIAL                             66
Q&A




CONFIDENTIAL   67
Thank you!

https://github.com/cbeams/distyles
http://twitter.com/cbeams




                         CONFIDENTIAL   68
Groovy/Grails BeanBuilder




          CONFIDENTIAL      69
BeanBuilder

 DSL for creating Spring BeanDefinitions
 Currently part of Grails
 Work is underway to include within Spring 3.1




                               CONFIDENTIAL       70
Grails BeanBuilder at a Glance

import org.springframework.context.ApplicationContext
import grails.spring.BeanBuilder
...
def bb = new BeanBuilder()

bb.beans {
  transferService(TransferServiceImpl, accountRepository, feePolicy)
  accountRepository(JdbcAccountRepository, dataSource)
  dataSource(BasicDataSource) {
     driverClassName = "org.hsqldb.jdbcDriver"
     url = "jdbc:hsqldb:mem:grailsDB"
     username = "sa"
     password = ""
  }
}

ApplicationContext ctx = bb.createApplicationContext();
TransferService transferService = ctx.getBean(TransferService);




                                     CONFIDENTIAL                      71
@Configuration: Summary

1.External vs. Internal: External
2.Explicit vs. Implicit: Explicit
3.Type-safe: No
4.Noninvasive: Yes
5.Portable: Yes
6.Can configure 3rd party components: Yes
7.Has tooling support: No




                                    CONFIDENTIAL   72

Weitere ähnliche Inhalte

Was ist angesagt?

Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-aNiit Care
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Svetlin Nakov
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJBodedns
 
EJB 3.1 by Bert Ertman
EJB 3.1 by Bert ErtmanEJB 3.1 by Bert Ertman
EJB 3.1 by Bert ErtmanStephan Janssen
 
JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6Bert Ertman
 
Spring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsSpring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsVMware Tanzu
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckTheo Jungeblut
 
Java Enterprise Edition 6 Overview
Java Enterprise Edition 6 OverviewJava Enterprise Edition 6 Overview
Java Enterprise Edition 6 OverviewEugene Bogaart
 
Chris meyer gl wand - financial reporting in excel
Chris meyer   gl wand - financial reporting in excelChris meyer   gl wand - financial reporting in excel
Chris meyer gl wand - financial reporting in excelBerry Clemens
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID CodeAdil Mughal
 
Free EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggetsFree EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggetsVirtual Nuggets
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring FrameworkMehul Jariwala
 
Mike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns FrameworksMike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns Frameworksukdpe
 
Spring Framework Rohit
Spring Framework RohitSpring Framework Rohit
Spring Framework RohitRohit Prabhakar
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJBPeter R. Egli
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009kensipe
 

Was ist angesagt? (20)

Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Java EE EJB Applications
Java EE EJB ApplicationsJava EE EJB Applications
Java EE EJB Applications
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJB
 
EJB 3.1 by Bert Ertman
EJB 3.1 by Bert ErtmanEJB 3.1 by Bert Ertman
EJB 3.1 by Bert Ertman
 
JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6
 
Spring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsSpring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden Gems
 
Maven
MavenMaven
Maven
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
 
Java Enterprise Edition 6 Overview
Java Enterprise Edition 6 OverviewJava Enterprise Edition 6 Overview
Java Enterprise Edition 6 Overview
 
Java vs .Net
Java vs .NetJava vs .Net
Java vs .Net
 
Chris meyer gl wand - financial reporting in excel
Chris meyer   gl wand - financial reporting in excelChris meyer   gl wand - financial reporting in excel
Chris meyer gl wand - financial reporting in excel
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID Code
 
Free EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggetsFree EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggets
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Mike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns FrameworksMike Taulty MIX10 Silverlight 4 Patterns Frameworks
Mike Taulty MIX10 Silverlight 4 Patterns Frameworks
 
Spring Framework Rohit
Spring Framework RohitSpring Framework Rohit
Spring Framework Rohit
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009
 

Ähnlich wie Dependency Injection Styles

CDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily JiangCDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily Jiangmfrancis
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI InteropRay Ploski
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmpEmily Jiang
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfBruceLee275640
 
Migrate to microservices
Migrate to microservicesMigrate to microservices
Migrate to microservicesAndrey Trubitsyn
 
Wahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash CourseWahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash Courseeightbit
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 
CrikeyCon 2015 - iOS Runtime Hacking Crash Course
CrikeyCon 2015 - iOS Runtime Hacking Crash CourseCrikeyCon 2015 - iOS Runtime Hacking Crash Course
CrikeyCon 2015 - iOS Runtime Hacking Crash Courseeightbit
 
Laying the Foundation for Ionic Platform Insights on Spark
Laying the Foundation for Ionic Platform Insights on SparkLaying the Foundation for Ionic Platform Insights on Spark
Laying the Foundation for Ionic Platform Insights on SparkIonic Security
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkASG
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentationAhasanul Kalam Akib
 
Continuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with Concourse
Continuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with ConcourseContinuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with Concourse
Continuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with ConcourseVMware Tanzu
 
Docker Kubernetes Istio
Docker Kubernetes IstioDocker Kubernetes Istio
Docker Kubernetes IstioAraf Karsh Hamid
 
CloudDesignPatterns
CloudDesignPatternsCloudDesignPatterns
CloudDesignPatternsOliver Fierro
 
Software Architecture and Architectors: useless VS valuable
Software Architecture and Architectors: useless VS valuableSoftware Architecture and Architectors: useless VS valuable
Software Architecture and Architectors: useless VS valuableComsysto Reply GmbH
 
9 - Making Sense of Containers in the Microsoft Cloud
9 - Making Sense of Containers in the Microsoft Cloud9 - Making Sense of Containers in the Microsoft Cloud
9 - Making Sense of Containers in the Microsoft CloudKangaroot
 
Transforming to Microservices
Transforming to MicroservicesTransforming to Microservices
Transforming to MicroservicesKyle Brown
 
Docker12 factor
Docker12 factorDocker12 factor
Docker12 factorJohn Zaccone
 

Ähnlich wie Dependency Injection Styles (20)

CDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily JiangCDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily Jiang
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI Interop
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmp
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
Migrate to microservices
Migrate to microservicesMigrate to microservices
Migrate to microservices
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Wahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash CourseWahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash Course
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
CrikeyCon 2015 - iOS Runtime Hacking Crash Course
CrikeyCon 2015 - iOS Runtime Hacking Crash CourseCrikeyCon 2015 - iOS Runtime Hacking Crash Course
CrikeyCon 2015 - iOS Runtime Hacking Crash Course
 
Laying the Foundation for Ionic Platform Insights on Spark
Laying the Foundation for Ionic Platform Insights on SparkLaying the Foundation for Ionic Platform Insights on Spark
Laying the Foundation for Ionic Platform Insights on Spark
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
 
Continuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with Concourse
Continuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with ConcourseContinuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with Concourse
Continuous Delivery: Fly the Friendly CI in Pivotal Cloud Foundry with Concourse
 
Docker Kubernetes Istio
Docker Kubernetes IstioDocker Kubernetes Istio
Docker Kubernetes Istio
 
CloudDesignPatterns
CloudDesignPatternsCloudDesignPatterns
CloudDesignPatterns
 
Software Architecture and Architectors: useless VS valuable
Software Architecture and Architectors: useless VS valuableSoftware Architecture and Architectors: useless VS valuable
Software Architecture and Architectors: useless VS valuable
 
9 - Making Sense of Containers in the Microsoft Cloud
9 - Making Sense of Containers in the Microsoft Cloud9 - Making Sense of Containers in the Microsoft Cloud
9 - Making Sense of Containers in the Microsoft Cloud
 
Transforming to Microservices
Transforming to MicroservicesTransforming to Microservices
Transforming to Microservices
 
Docker12 factor
Docker12 factorDocker12 factor
Docker12 factor
 

KĂźrzlich hochgeladen

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

KĂźrzlich hochgeladen (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Dependency Injection Styles

  • 1. DI Styles: Choosing the Right Tool for the Job Chris Beams, Senior Technical Staff, SpringSource CONFIDENTIAL Š 2010 SpringSource, A division of VMware. All rights reserved
  • 2. Hello!  Chris Beams • Senior Staff Engineer with SpringSource • Member Core Spring team • Trained hundreds to use Spring effectively • Author of the forthcoming Spring in a Nutshell (O'Reilly) CONFIDENTIAL 2
  • 3. Dependency Injection: Simple, Right? TransferService AccountRepository public TransferService(AccountRepository ar) { this.accountRepository = ar; } CONFIDENTIAL 3
  • 4. Choices @Configuration @Autowired <context:annotation-config/> @Bean <context:component-scan/> @Inject @Component @Configurable <bean/> ... CONFIDENTIAL 4
  • 5. Agenda  A brief history of Dependency Injection (DI)  Seven characteristics of a DI style  A demo-centric tour of Spring DI styles • Comparative analysis of available styles • What's new in Spring 3 for DI • Demo sources available at: • http://github.com/cbeams/distyles CONFIDENTIAL 5
  • 6. Agenda  A brief history of Dependency Injection (DI)  Seven characteristics of a DI style  A demo-centric tour of Spring DI styles • Comparative analysis of available styles • What's new in Spring 3 for DI • Demo sources available at: • https://src.springsource.org/svn/springone2gx/distyles CONFIDENTIAL 6
  • 7. Agenda  A brief history of Dependency Injection (DI)  Seven characteristics of a DI style  A demo-centric tour of Spring DI styles • Comparative analysis of available styles • What's new in Spring 3 for DI • Demo sources available online • http://github.org/cbeams/distyles CONFIDENTIAL 7
  • 8. A one-slide history of DI  2000: Fowler, et al coin 'POJO'  2002: Johnson, et al: 1:1 J2EE; J2EE w/o EJB  2002-3: Spring and other 'lightweight IoC containers' emerge  2004: Fowler coins 'Dependency Injection as a specialization of the Inversion of Control principle' • Defined three 'types' of DI • Constructor Injection • Setter Injection • Interface Injection  2004-present: Spring evolves; DI is widely adopted CONFIDENTIAL 8
  • 9. DI: Why?  Dependency Injection enables 'POJO programming'  POJO programming facilitates • Simplicity • Effective separation of concerns • Proper unit testing  Well-factored and well-tested code • Tends to be well-designed code • Evolves well into maintainable systems CONFIDENTIAL 9
  • 10. DI: Where to Inject?  Three possible 'Injection Points' • Constructor • Good for mandatory dependencies • Setter • Good for optional dependencies • Field • Good for injecting system test fixtures in JUnit tests CONFIDENTIAL 10
  • 11. DI: How to Configure?  Styles for expressing DI metadata and instructions • External • Configuration files (XML, properties, ...) • Code (Java) • DSL (Spring XML namespaces, Groovy, ...) • Internal • Annotations embedded within POJOs • Usually requires at least some external configuration CONFIDENTIAL 11
  • 12. DI: Evolution  We've come a long way since Fowler coined DI  Today developers are faced with many choices • Annotations changed the game • Rise of non-Java languages on the JVM creates new possibilities CONFIDENTIAL 12
  • 13. DI: Today's Choices  Open-source projects • Spring • Grails BeanBuilder • Google Guice • Many other projects across languages  Standards efforts • JSR-250 (Common Annotations) • JSR-299 (Java Contexts and Dependency Injection) • JSR-330 (Dependency Injection for Java) • OSGi 4.2 Blueprint Container CONFIDENTIAL 13
  • 14. Choosing a DI Style CONFIDENTIAL 14
  • 15. DI Configuration: What matters to you?  Let's begin by defining the characteristics that matter when thinking about DI  Provide a framework for making decisions about your own applications CONFIDENTIAL 15
  • 16. Seven Characteristics of a DI Style 1.External vs. Internal 2.Explicit vs. Implicit 3.Type-safety 4.Noninvasiveness 5.Portability (of POJOs) 6.Configurability of 3rd party components 7.Tooling support CONFIDENTIAL 16
  • 17. Characteristic 1: External vs. Internal External <bean id=“transferService” class=“com.bank.TransferServiceImpl”> <constructor-arg ref=“accountRepository” /> </bean> Internal @Component public class TransferServiceImpl implements TransferService { @Autowired public TransferServiceImpl(AccountRepository repo) { this.accountRepository = repo; } … } CONFIDENTIAL 17
  • 18. Characteristic 1: External vs. Internal  External DI is noninvasive • But causes context-switching during coding • More verbose • Provides a 'blueprint' of your application  Internal DI is necessarily invasive • May or may not be portable • But requires less coding and maintenance • Easier to use during development CONFIDENTIAL 18
  • 19. Seven Characteristics of a DI Style 1.External vs. Internal 2.Explicit vs. Implicit 3.Type-safety 4.Noninvasiveness 5.Portability (of POJOs) 6.Configurability of 3rd party components 7.Tooling support CONFIDENTIAL 19
  • 20. Characteristic 2: Explicit vs. Implicit <bean id=“transferService” class=“com.bank.TransferServiceImpl”> <constructor-arg ref=“accountRepository” /> <constructor-arg ref=“feePolicy” /> </bean> <bean id=“accountRepository” class=“com.bank.JdbcAccountRepository”> <bean id=“feePolicy” class=“com.bank.FlatFeePolicy”> public class TransferServiceImpl implements TransferService { public TransferServiceImpl(AccountRepository accountRepository, FeePolicy feePolicy) { … } … } CONFIDENTIAL 20
  • 21. Characteristic 2: Explicit vs. Implicit <context:component-scan base-package=“com.bank"> @Component public class TransferServiceImpl implements TransferService { @Autowired public TransferServiceImpl(AccountRepository accountRepository, FeePolicy feePolicy) { … } … } @Component public class JdbcAccountRepository implements AccountRepository{ … } @Component public class FlatFeePolicy implements FeePolicy{ … } CONFIDENTIAL 21
  • 22. Characteristic 2: Explicit vs. Implicit  Explicit DI comes with greater verbosity • More tedious in simple cases • Easier and more clear when things get complicated  Implicit DI introduces the possibility of ambiguity • If multiple implementations of a given type are detected / scanned • Disambiguation strategies are required • But ambiguities may arise at any time CONFIDENTIAL 22
  • 23. Explicit vs. Implicit: Ambiguity <context:component-scan base-package=“com.bank"> @Component public class TransferServiceImpl implements TransferService { @Autowired public TransferServiceImpl(AccountRepository accountRepository, FeePolicy feePolicy) { … } … } @Component public class JdbcAccountRepository implements AccountRepository{ … } @Component public class FlatFeePolicy implements FeePolicy{ … } Which one should get @Component injected? public class VariableFeePolicy implements FeePolicy{ … } CONFIDENTIAL 23
  • 24. Implicit DI: Disambiguation <context:component-scan base-package=“com.bank"> @Component public class TransferServiceImpl implements TransferService { @Autowired public TransferServiceImpl(AccountRepository repo, @Qualifer(“domestic”) FeePolicy feePolicy) { … } … } @Component public class JdbcAccountRepository implements AccountRepository{ … } @Component @Qualifier(“domestic”) public class FlatFeePolicy implements FeePolicy{ … } @Component(“international”) public class VariableFeePolicy implements FeePolicy{ … } CONFIDENTIAL 24
  • 25. Seven Characteristics of a DI Style 1.External vs. Internal 2.Explicit vs. Implicit 3.Type-safety 4.Noninvasiveness 5.Portability (of POJOs) 6.Configurability of 3rd party components 7.Tooling support CONFIDENTIAL 25
  • 26. Characteristic 3: Type-safety  XML is inherently not type-safe • Tooling can mitigate this • STS/IDEA/NetBeans are Spring XML-aware and can raise warnings and errors at development time  How can one get the compiler to catch errors in DI configuration? • Custom @Qualifier annotations • @Configuration classes CONFIDENTIAL 26
  • 27. Seven Characteristics of a DI Style 1.External vs. Internal 2.Explicit vs. Implicit 3.Type-safety 4.Noninvasiveness 5.Portability (of POJOs) 6.Configurability of 3rd party components 7.Tooling support CONFIDENTIAL 27
  • 28. Characteristic 4: (Non)invasiveness  Originally, noninvasiveness was a defining characteristic of DI and POJO programming  Noninvasiveness matters because • An object should be usable independent of its environment and context • Especially important when it comes to testing  But... • Annotations changed this CONFIDENTIAL 28
  • 29. Annotations and Invasiveness  Annotations, by definition, are invasive • Requires modifying POJOs  But we may say they are minimally invasive • Because annotations have no detrimental effect on the utility of a POJO • Java 6 even allows for annotations to be missing from the classpath at runtime  Non-standard annotations still impact portability CONFIDENTIAL 29
  • 30. Seven Characteristics of a DI Style 1.External vs. Internal 2.Explicit vs. Implicit 3.Type-safety 4.Noninvasiveness 5.Portability (of POJOs) 6.Configurability of 3rd party components 7.Tooling support CONFIDENTIAL 30
  • 31. Characteristic 5: Portability  Ideally, a POJO should be reusable across DI frameworks  Non-standard annotations tie you to a particular framework • Hence the desire for standardization • JSR-330! CONFIDENTIAL 31
  • 32. Seven Characteristics of a DI Style 1.External vs. Internal 2.Explicit vs. Implicit 3.Type-safety 4.Noninvasiveness 5.Portability (of POJOs) 6.Configurability of 3rd party components 7.Tooling support CONFIDENTIAL 32
  • 33. Characteristic 6: Configurability of 3rd Party Components  Internal configuration and 3rd party components don't mix • You can't annotate somebody else's code  External configuration is the only way • Hence a complete DI solution must support both CONFIDENTIAL 33
  • 34. Seven Characteristics of a DI Style 1.External vs. Internal 2.Explicit vs. Implicit 3.Type-safety 4.Noninvasiveness 5.Portability (of POJOs) 6.Configurability of 3rd party components 7.Tooling support CONFIDENTIAL 34
  • 35. Characteristic 7: Tooling Support  Natural, integrated refactoring • XML-driven DI requires Spring-aware tooling • Code-driven DI takes advantage of built-in IDE Java tooling  Content Assist in configuration files • Generic XML tooling only gets you so far • Need XML tooling built to purpose  Visualization • Seeing the 'blueprint' of your application  Other concerns • Static analysis • Obfuscation CONFIDENTIAL 35
  • 36. SpringSource Tool Suite (STS) CONFIDENTIAL 36
  • 37. A Tour of DI Styles CONFIDENTIAL 37
  • 38. DI Styles  XML • <beans/> • <namespace:*/>  @Autowired  @Configuration  Standards • JSR-250 (Common Annotations) • JSR-299 (Java Contexts and Dependency Injection) • JSR-330 (Dependency Injection for Java) CONFIDENTIAL 38
  • 39. DI Styles  Remember... • DI styles need not be mutually exclusive! • You'll probably use more than one in a given app CONFIDENTIAL 39
  • 41. <beans/> XML  The original DI style for Spring  Remains very widely used  General-purpose, thus very powerful  But can get verbose / maintenance-intensive CONFIDENTIAL 41
  • 42. <beans/> demo CONFIDENTIAL 42
  • 43. <beans/>: Summary 1.External vs. Internal: External 2.Explicit vs. Implicit: Explicit 3.Type-safe: No 4.Noninvasive: Yes 5.Portable: Yes 6.Can configure 3rd party components: Yes 7.Has tooling support: Yes CONFIDENTIAL 43
  • 44. <namespace:*/> CONFIDENTIAL 44
  • 45. <namespace:*/> XML  Introduced in Spring 2.0  Expanded in Spring 2.5 and 3.0  Widely supported by Spring projects • Spring Integration • Spring Batch • Spring Web Flow • Spring Security • ...  Greatly reduces XML verbosity  More expressive at the same time CONFIDENTIAL 45
  • 46. <namespace:*/> demo CONFIDENTIAL 46
  • 47. <namespace:*/>: Summary  Same fundamental characteristics as <beans/>  But eliminates much of the verbosity problem with XML • Serves as a 'configuration DSL'  Not just about DI • Helps manage many other aspects of the application • Scheduling, AOP, security, etc. CONFIDENTIAL 47
  • 48. @Autowired CONFIDENTIAL 48
  • 49. @Autowired  AKA "Annotation-driven injection"  Introduced in Spring 2.5  More annotations added in Spring 3.0 • @Primary • @Lazy • @DependsOn • extended semantics for @Scope  Widely used today  Works in conjunction with @Component and <context:component- scan/> to streamline development lifecycle CONFIDENTIAL 49
  • 50. @Autowired demo CONFIDENTIAL 50
  • 51. @Autowired: Summary 1.External vs. Internal: Internal 2.Explicit vs. Implicit: Implicit 3.Type-safe: Yes 4.Noninvasive: No 5.Portable: No 6.Can configure 3rd party components: No 7.Has tooling support: Yes (as of STS 2.2.0) CONFIDENTIAL 51
  • 52. JSR-330 (@Inject) CONFIDENTIAL 52
  • 53. Introducing JSR-330  AKA @Inject  A joint JCP effort by Google and SpringSource  Provides common understanding of injection semantics through portable DI annotations  Packaged under javax.inject.* (Java SE)  JSR went final late 2009 • API is available in Maven Central  Spring 3.0 GA passes the TCK CONFIDENTIAL 53
  • 54. Smallest. JSR. Ever. CONFIDENTIAL 54
  • 55. JSR-330 demo CONFIDENTIAL 55
  • 56. JSR-330: Summary 1.External vs. Internal: Internal 2.Explicit vs. Implicit: Undefined! (can be either) 3.Type-safe: Yes 4.Noninvasive: No 5.Portable: Yes 6.Can configure 3rd party components: No 7.Has tooling support: Yes (STS) CONFIDENTIAL 56
  • 57. @Autowired and @Inject: The Bottom Line  JSR-330 standardizes internal DI annotations • Meaning: portable POJOs  However, @Inject is a subset of the functionality provided by Spring's @Autowired support  Rule of thumb • You can get 80% of what you need with @Inject • Rely on @Autowired and friends for the rest CONFIDENTIAL 57
  • 58. From @Autowired to @Inject Spring javax.inject.* @Autowired @Inject * @Inject has no 'required' attribute @Component @Named * Spring supports scanning for @Named @Scope @Scope * for meta-annotation and injection points only @Scope @Singleton * jsr-330 default scope is like Spring's 'prototype' ("singleton") @Qualifier @Qualifier, @Named @Value no equivalent see SPR-6251 for ideas on how Spring can help bridge this gap @Primary no equivalent @Lazy no equivalent @Required no equivalent CONFIDENTIAL 58
  • 59. @Configuration CONFIDENTIAL 59
  • 60. @Configuration  Formely Spring JavaConfig  Now included in core Spring Framework 3.0  Annotation-driven, but is an external DI style • POJOs remain untouched by annotations  Provides full programmatic control over object instantiation and DI  Allows for object-oriented configuration  Integrates well with other Spring DI styles CONFIDENTIAL 60
  • 61. A @Configuration class @Configuration public class AppCong { @Bean public TransferService transferService() { return new TransferService(accountRepository()); } @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource()); } // ... } CONFIDENTIAL 61
  • 62. Look familiar? <bean id=“transferService” class=“com.bank.TransferServiceImpl”> <constructor-arg ref=“accountRepo” /> </bean> <bean id=“accountRepo” class=“com.bank.JdbcAccountRepository”> <constructor-arg ref=“dataSource” /> </bean> CONFIDENTIAL 62
  • 63. Bootstrapping @Configuration public class CommandLineApplication { public static void main(String... args) { ApplicationContext ctx = new AnnotationCongApplicationContext(AppCong.class); TransferService transferService = ctx.getBean(TransferService.class); transferService.transfer(100.00, “A123”, “C456”); } } CONFIDENTIAL 63
  • 64. @Configuration demo CONFIDENTIAL 64
  • 65. @Configuration: Summary 1.External vs. Internal: External 2.Explicit vs. Implicit: Explicit 3.Type-safe: Yes 4.Noninvasive: Yes 5.Portable: Yes 6.Can configure 3rd party components: Yes 7.Has tooling support: Yes CONFIDENTIAL 65
  • 66. Spring is about choice  Choice in many areas...  All DI metadata (internal or external) contributes to the core BeanDefinition model • This layer is what makes adding different configurations styles possible!  Spring embraces any relevant deployment environment • Use latest DI/EE6 styles on • J2EE 1.5 and JEE 5 • OSGi CONFIDENTIAL 66
  • 69. Groovy/Grails BeanBuilder CONFIDENTIAL 69
  • 70. BeanBuilder  DSL for creating Spring BeanDefinitions  Currently part of Grails  Work is underway to include within Spring 3.1 CONFIDENTIAL 70
  • 71. Grails BeanBuilder at a Glance import org.springframework.context.ApplicationContext import grails.spring.BeanBuilder ... def bb = new BeanBuilder() bb.beans { transferService(TransferServiceImpl, accountRepository, feePolicy) accountRepository(JdbcAccountRepository, dataSource) dataSource(BasicDataSource) { driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" password = "" } } ApplicationContext ctx = bb.createApplicationContext(); TransferService transferService = ctx.getBean(TransferService); CONFIDENTIAL 71
  • 72. @Configuration: Summary 1.External vs. Internal: External 2.Explicit vs. Implicit: Explicit 3.Type-safe: No 4.Noninvasive: Yes 5.Portable: Yes 6.Can configure 3rd party components: Yes 7.Has tooling support: No CONFIDENTIAL 72