Dependency Injection
          with Spring




Presenter: Danil Kornishev   1
Introduction

• DI is a defined methodology
• DI is needed
• DI is not magical




                            2
Conceptual Model



                     Interface           Programming to an Interface
Deployment




                                         creates need for a wiring
             Impl1    Impl2      Impl3   component in the deployment layer




                                                                        3
Bean Definition
<bean id="sslContextFactory" class="com.db.fw.entl.remoteClient.rest.impl.ssl.EtlSSLConfig“ scope="prototype" >
             <property name="keyStoreFile" value="certs/keystore_rds" />
             <property name="keyStorePass" ref="password" />
             <property name="trustStoreFile" value="certs/truststore_rds" />
             <property name="trustStorePass" ref="password" />
</bean>
<bean id="serviceLocator" class="com.db.fw.entl.locator.LoadAwareHTTPServiceLocator" init-method="startPolling">
<constructor-arg>
      <map>
             <entry key="READ_SERVICE">
                   <bean class="java.lang.String">
                         <constructor-arg value="https://localhost:1998" />
                   </bean>
             </entry>
      </map>
</constructor-arg>
<constructor-arg value="300000" />
<constructor-arg name="sslCtx">
             <bean factory-bean="sslContextFactory" factory-method="createSSLContext" />
</constructor-arg>
</bean>
<bean id="staticFactoryCreated" class="com.static.factory" factory-method="newSSLContext" destroy-method="close" />




 Beans        Constructor         Factory bean            Init
                                                                         Scope
 Inline        Property           Static Factory        Destroy
                                                                                                             4
Additional Initialization

              • @PostConstruct
Annotations




                 • Invoked when DI is finished
              • @PreDestroy
                 • Invoked before context is destroyed
                                @PostConstruct
                                public void warmup()
                 Init/Cleanup




                                {
                                    // initialize using injected properties
                                }

                                @PreDestroy
                                public void teardown()
                                {
                                    // close connections, send notifications...etc
                                }




                                                                                     5
Collections
        <list>                                                <util:list id="emails">
              <value>pechorin@hero.org</value>                          <value>pechorin@hero.org</value>
Lists




              <value>raskolnikov@slums.org</value>                      <value>raskolnikov@slums.org</value>
              <value>stavrogin@gov.org</value>                          <value>stavrogin@gov.org</value>
              <value>porfiry@gov.org</value>                            <value>porfiry@gov.org</value>
        </list>                                               </util:list>


        <set>                                                 <util:set id="emails">
                 <value>pechorin@hero.org</value>                      <value>pechorin@hero.org</value>
Sets




                 <value>raskolnikov@slums.org</value>                  <value>raskolnikov@slums.org</value>
                 <value>stavrogin@gov.org</value>                      <value>stavrogin@gov.org</value>
                 <value>porfiry@gov.org</value>                        <value>porfiry@gov.org</value>
        </set>                                                </util:set>


        <map>                                                 <util:map id="emails">
              <entry   key="pec" value=“chorin@hero.org"/>            <entry key="pech" value=“chorin@hero.org"/>
Maps




              <entry   key="rask" value="rask@slums.org"/>            <entry key="rask" value="rask@slums.org"/>
              <entry   key="starogin" value=“sn@gov.org"/>            <entry key="stavrogin" value=“sn@gov.org"/>
              <entry   key="porfiry" value=“iry@gov.org"/>            <entry key="porfiry" value=“iry@gov.org"/>
        </map>                                                </util:map>


                                                Inline         Stand-Alone




                                                                                                               6
Spring Context Usage
Create the Context
ApplicationContext ctx = new ClassPathXmlApplicationContext("/path/to/config1.xml","/path/to/config2.xml");




 Obtain the Bean
ServiceLocator locator = (ServiceLocator)ctx.getBean("serviceLocator");




         Use
URL sererHost = locator.locate("myservice");




 Close when done
ctx.close();




                                                                                                          7
Raising Context Awareness
 Create a class that implements Context Awareness
class SpringContext implements ApplicationContextAware
{
            @Override
            public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
            {
                        // Do something like caching the context
            }
}




           Reference it in a configuration file
<bean id="contextAware" class="com.db.fw.entl.context.SpringContext" />




Now, when Spring is done loading the context, it
will invoke SpringContext.setApplicationContext
passing in the context created.

                                                                                                             8
Life after XML




Spring 3 allows Java-only configuration
Define beans using familiar language
No XML files -- live XML-free




                                      9
Spring 3 Annotations

    • @Configuration
       • Marks a class as a bean provider
    • @Bean
       • Marks a method as a bean provider
    • @Lazy, @Scope, @Primary
       • Same goodies you know and love
    • @ImportResource
       • Interoperability with Spring XML
@Configuration   @Lazy       @Primary

@Bean            @Scope      @ImportResource
                                                 10
Java-only Bean Factory
@Configuration
public class AnnotationConfiguredBeans
{
     @Bean
     public String greeting()
     {
         return "Hello World ";
     }

     @Primary
     @Bean
     @Lazy
     public ComplexValue complex()
     {
         return new ComplexValue(simpleValue1(), simpleValue2());
     }

     @Bean
     @Scope(BeanDefinition.SCOPE_PROTOTYPE)
     public SimpleValue simpleValue1()
     {
         return new SimpleValue("Good Bye“, Math.random()*1000);
     }
}




                                                                    11
Annotation Driven Context
Create the Context
ApplicationContext ac = new AnnotationConfigApplicationContext(AnnotationConfiguredBeans.class);




                                     Use it in the same way as you
                                     would an XML generated context.
                                     Programming to an interface
                                     works!
                                     Freedom from the XML tyranny!



                                                                                                   12
Alternative DI Frameworks




EJB 3.0                  Google Guice




                                        13
Q&A

      14

Spring dependency injection

  • 1.
    Dependency Injection with Spring Presenter: Danil Kornishev 1
  • 2.
    Introduction • DI isa defined methodology • DI is needed • DI is not magical 2
  • 3.
    Conceptual Model Interface Programming to an Interface Deployment creates need for a wiring Impl1 Impl2 Impl3 component in the deployment layer 3
  • 4.
    Bean Definition <bean id="sslContextFactory"class="com.db.fw.entl.remoteClient.rest.impl.ssl.EtlSSLConfig“ scope="prototype" > <property name="keyStoreFile" value="certs/keystore_rds" /> <property name="keyStorePass" ref="password" /> <property name="trustStoreFile" value="certs/truststore_rds" /> <property name="trustStorePass" ref="password" /> </bean> <bean id="serviceLocator" class="com.db.fw.entl.locator.LoadAwareHTTPServiceLocator" init-method="startPolling"> <constructor-arg> <map> <entry key="READ_SERVICE"> <bean class="java.lang.String"> <constructor-arg value="https://localhost:1998" /> </bean> </entry> </map> </constructor-arg> <constructor-arg value="300000" /> <constructor-arg name="sslCtx"> <bean factory-bean="sslContextFactory" factory-method="createSSLContext" /> </constructor-arg> </bean> <bean id="staticFactoryCreated" class="com.static.factory" factory-method="newSSLContext" destroy-method="close" /> Beans Constructor Factory bean Init Scope Inline Property Static Factory Destroy 4
  • 5.
    Additional Initialization • @PostConstruct Annotations • Invoked when DI is finished • @PreDestroy • Invoked before context is destroyed @PostConstruct public void warmup() Init/Cleanup { // initialize using injected properties } @PreDestroy public void teardown() { // close connections, send notifications...etc } 5
  • 6.
    Collections <list> <util:list id="emails"> <value>pechorin@hero.org</value> <value>pechorin@hero.org</value> Lists <value>raskolnikov@slums.org</value> <value>raskolnikov@slums.org</value> <value>stavrogin@gov.org</value> <value>stavrogin@gov.org</value> <value>porfiry@gov.org</value> <value>porfiry@gov.org</value> </list> </util:list> <set> <util:set id="emails"> <value>pechorin@hero.org</value> <value>pechorin@hero.org</value> Sets <value>raskolnikov@slums.org</value> <value>raskolnikov@slums.org</value> <value>stavrogin@gov.org</value> <value>stavrogin@gov.org</value> <value>porfiry@gov.org</value> <value>porfiry@gov.org</value> </set> </util:set> <map> <util:map id="emails"> <entry key="pec" value=“chorin@hero.org"/> <entry key="pech" value=“chorin@hero.org"/> Maps <entry key="rask" value="rask@slums.org"/> <entry key="rask" value="rask@slums.org"/> <entry key="starogin" value=“sn@gov.org"/> <entry key="stavrogin" value=“sn@gov.org"/> <entry key="porfiry" value=“iry@gov.org"/> <entry key="porfiry" value=“iry@gov.org"/> </map> </util:map> Inline Stand-Alone 6
  • 7.
    Spring Context Usage Createthe Context ApplicationContext ctx = new ClassPathXmlApplicationContext("/path/to/config1.xml","/path/to/config2.xml"); Obtain the Bean ServiceLocator locator = (ServiceLocator)ctx.getBean("serviceLocator"); Use URL sererHost = locator.locate("myservice"); Close when done ctx.close(); 7
  • 8.
    Raising Context Awareness Create a class that implements Context Awareness class SpringContext implements ApplicationContextAware { @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // Do something like caching the context } } Reference it in a configuration file <bean id="contextAware" class="com.db.fw.entl.context.SpringContext" /> Now, when Spring is done loading the context, it will invoke SpringContext.setApplicationContext passing in the context created. 8
  • 9.
    Life after XML Spring3 allows Java-only configuration Define beans using familiar language No XML files -- live XML-free 9
  • 10.
    Spring 3 Annotations • @Configuration • Marks a class as a bean provider • @Bean • Marks a method as a bean provider • @Lazy, @Scope, @Primary • Same goodies you know and love • @ImportResource • Interoperability with Spring XML @Configuration @Lazy @Primary @Bean @Scope @ImportResource 10
  • 11.
    Java-only Bean Factory @Configuration publicclass AnnotationConfiguredBeans { @Bean public String greeting() { return "Hello World "; } @Primary @Bean @Lazy public ComplexValue complex() { return new ComplexValue(simpleValue1(), simpleValue2()); } @Bean @Scope(BeanDefinition.SCOPE_PROTOTYPE) public SimpleValue simpleValue1() { return new SimpleValue("Good Bye“, Math.random()*1000); } } 11
  • 12.
    Annotation Driven Context Createthe Context ApplicationContext ac = new AnnotationConfigApplicationContext(AnnotationConfiguredBeans.class); Use it in the same way as you would an XML generated context. Programming to an interface works! Freedom from the XML tyranny! 12
  • 13.
    Alternative DI Frameworks EJB3.0 Google Guice 13
  • 14.
    Q&A 14