SlideShare uma empresa Scribd logo
1 de 14
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

Mais conteúdo relacionado

Mais procurados

Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questionsArun Vasanth
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview QuestionsSyed Shahul
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Fahad Golra
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization Hitesh-Java
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationKhoa Nguyen
 

Mais procurados (17)

Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Spring framework DAO
Spring framework  DAOSpring framework  DAO
Spring framework DAO
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Spring
SpringSpring
Spring
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questions
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Hibernate
HibernateHibernate
Hibernate
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
 

Destaque

Spring and dependency injection
Spring and dependency injectionSpring and dependency injection
Spring and dependency injectionSteve Ng
 
Implement Dependency Injection in Java
Implement Dependency Injection in JavaImplement Dependency Injection in Java
Implement Dependency Injection in JavaGeng-Dian Huang
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Androidgreenrobot
 
A Brief presentation on Containerisation
A Brief presentation on ContainerisationA Brief presentation on Containerisation
A Brief presentation on Containerisationsubhash_ae
 

Destaque (11)

Spring and dependency injection
Spring and dependency injectionSpring and dependency injection
Spring and dependency injection
 
Implement Dependency Injection in Java
Implement Dependency Injection in JavaImplement Dependency Injection in Java
Implement Dependency Injection in Java
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Dagger 2
Dagger 2Dagger 2
Dagger 2
 
Types of containers
Types of  containersTypes of  containers
Types of containers
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
 
Types of containers
Types of containers Types of containers
Types of containers
 
A Brief presentation on Containerisation
A Brief presentation on ContainerisationA Brief presentation on Containerisation
A Brief presentation on Containerisation
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 

Semelhante a Spring dependency injection

Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qconYiwei Ma
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityWashington Botelho
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache AntShih-Hsiang Lin
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Gunith Devasurendra
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfAppster1
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfAppster1
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 

Semelhante a Spring dependency injection (20)

Play 2.0
Play 2.0Play 2.0
Play 2.0
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qcon
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 
Spring 3.1
Spring 3.1Spring 3.1
Spring 3.1
 
Play framework
Play frameworkPlay framework
Play framework
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 

Último

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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
 
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
 
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
 

Último (20)

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
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...
 
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
 

Spring dependency injection

  • 1. Dependency Injection with Spring Presenter: Danil Kornishev 1
  • 2. Introduction • DI is a 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 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
  • 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 Spring 3 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 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
  • 12. 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
  • 13. Alternative DI Frameworks EJB 3.0 Google Guice 13
  • 14. Q&A 14