SlideShare uma empresa Scribd logo
1 de 16
Dependency Injection with Spring
in 10 minutes
Corneil du Plessis
corneil.duplessis@gmail.com
@corneil
Introduction
● Assumptions
– You have some appreciation of component-oriented
development
– You have seen Java code
– You have heard of the Spring Framework or Dependency
Injection
● Take away
– Some appreciation for benefits of dependency injection
– Some understanding of how Spring supports dependency
injection.
What is Dependency Injection?
● Robert C Martin and Martin Fowler has written some of the best
articles on the subject.
● Dependency Injection is also known as Inversion of Control or
Dependency Inversion.
● DI is a specific form of IoC.
● When an object is composed the responsibility for composing the
dependents of the object is not handled by the specific object.
● Modern applications uses one or more containers or frameworks to
take care of DI.
● Examples are EJB container and Spring Framework.
● We will look at mechanisms provider by Spring Framework
What is Spring Framework?
● The Spring Framework provides support for a large
number of useful programming patterns.
● Patterns in questions are:
– Singleton
– Factory
– Locator
– Visitor
DI – Best Practice
● Required unchanging dependencies via constructor.
● Assemble and fail early
● Be careful of the cost of DI frameworks.
– Don't use to create Data Transfer Objects.
DI – Sample Classes
DI – Sample Objects
DI – Code without DI
public ProfileDataAccessComponent() throws NamingException, FileNotFoundException, IOException {
super();
// In EJB or Web Container
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/profile");
} catch(Throwable x) {
// Assume we are not in container.
}
if(dataSource == null) {
// Manual creation outside of container
Properties props = new Properties();
File propFile = new File("db.properties");
props.load(new FileInputStream(propFile));
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(props.getProperty("db.driver"));
ds.setUsername(props.getProperty("db.username"));
ds.setPassword(props.getProperty("db.password"));
ds.setUrl(props.getProperty("db.url"));
ds.setMaxActive(Integer.parseInt(props.getProperty("db.maxActive", "10")));
ds.setMaxIdle(Integer.parseInt(props.getProperty("db.maxIdle", "5")));
ds.setInitialSize(Integer.parseInt(props.getProperty("db.initialSize", "5")));
ds.setValidationQuery(props.getProperty("db.validationQuery", "SELECT 1"));
dataSource = ds;
}
}
DI – More Code
public ProfileNotificationSender() throws NamingException {
super();
InitialContext ctx = new InitialContext();
factory = (ConnectionFactory)
ctx.lookup("java:comp/env/jms/queue/ConnectionFactory");
destination = (Destination) ctx.lookup("java:comp/env/jms/queue/Profile");
}
DI – Spring Beans from XML
<context:property-placeholder location="db.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="profileDAC"
class="org.springframework.di.demo.ProfileDataAccessComponent">
<constructor-arg ref="dataSource" />
</bean>
DI – Spring Beans from XML
<jee:jndi-lookup id="destination" jndi-name="jms/queue/Profile"
expected-type="javax.jms.Destination" />
<jee:jndi-lookup id="connectionFactory" jndi-name="jms/queue/ConnectionFactory"
expected-type="javax.jms.ConnectionFactory" />
<bean id="notificationSender"
class="org.springframework.di.demo.ProfileNotificationSender">
<constructor-arg ref="connectionFactory" />
<constructor-arg ref="destination" />
</bean>
<bean id="profileService" class="org.springframework.di.demo.ProfileService">
<constructor-arg ref="profileDAC" />
<constructor-arg ref="notificationSender" />
</bean>
DI – Spring Annotations Config
<context:property-placeholder location="db.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<jee:jndi-lookup id="destination" jndi-name="jms/queue/Profile"
expected-type="javax.jms.Destination" />
<jee:jndi-lookup id="connectionFactory" jndi-name="jms/queue/ConnectionFactory"
expected-type="javax.jms.ConnectionFactory" />
<context:component-scan base-package="org.springframework.di.autowire" />
DI – Spring Annotations Code
@Autowired
public ProfileNotificationSender(ConnectionFactory factory,
Destination destination) {
super();
this.factory = factory;
this.destination = destination;
}
@Service("profileService")
public class ProfileService implements ProfileInteface {
private ProfileDataAccessInterface dataAccess;
private ProfileNotificationInterface notification;
@Autowired
public ProfileService(ProfileDataAccessInterface dataAccess,
ProfileNotificationInterface notification) {
super();
this.dataAccess = dataAccess;
this.notification = notification;
}
DI – Spring Java Config
@Configuration
public class AppConfig {
@Autowired
Environment env;
@Bean
public Destination destination() {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("jms/queue/Profile");
bean.setExpectedType(Destination.class);
return (Destination) bean.getObject();
}
@Bean
public ConnectionFactory connectionFactory() {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("jms/queue/ConnectionFactory");
bean.setExpectedType(ConnectionFactory.class);
return (ConnectionFactory) bean.getObject();
}
}
DI – Spring Java Config
@Configuration
@PropertySource("db.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("db.driver"));
dataSource.setUrl(env.getProperty("db.url"));
dataSource.setUsername(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("db.password"));
return dataSource;
}
}
Questions
● Demo code at
https://github.com/corneil/demos/tree/master/spring-di-sample
● Discuss on JUG Facebook https://www.facebook.com/groups/jozijug
● Discuss on JUG Meetup

Mais conteúdo relacionado

Mais procurados

Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questionsArun Vasanth
 
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
 
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
 
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
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot missMark Papis
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qconYiwei Ma
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 

Mais procurados (16)

Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questions
 
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
 
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
 
Spring
SpringSpring
Spring
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
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
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qcon
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 

Destaque

Spring and dependency injection
Spring and dependency injectionSpring and dependency injection
Spring and dependency injectionSteve Ng
 
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
 
A Brief presentation on Containerisation
A Brief presentation on ContainerisationA Brief presentation on Containerisation
A Brief presentation on Containerisationsubhash_ae
 

Destaque (6)

Spring and dependency injection
Spring and dependency injectionSpring and dependency injection
Spring and dependency injection
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
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
 
Types of containers
Types of  containersTypes of  containers
Types of containers
 
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
 

Semelhante a Dependency Injection in Spring in 10min

D7 entities fields
D7 entities fieldsD7 entities fields
D7 entities fieldscyberswat
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMJonathan Wage
 
Java design patterns
Java design patternsJava design patterns
Java design patternsBrian Zitzow
 
Working with LoopBack Models
Working with LoopBack ModelsWorking with LoopBack Models
Working with LoopBack ModelsRaymond Feng
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreIMC Institute
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsRahul Malhotra
 
Drupalcon cph
Drupalcon cphDrupalcon cph
Drupalcon cphcyberswat
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
MicroProfile Devoxx.us
MicroProfile Devoxx.usMicroProfile Devoxx.us
MicroProfile Devoxx.usjclingan
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot trainingMallikarjuna G D
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 

Semelhante a Dependency Injection in Spring in 10min (20)

D7 entities fields
D7 entities fieldsD7 entities fields
D7 entities fields
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Working with LoopBack Models
Working with LoopBack ModelsWorking with LoopBack Models
Working with LoopBack Models
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Designing Testable Software
Designing Testable SoftwareDesigning Testable Software
Designing Testable Software
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
Introduction to Domain-Driven Design
Introduction to Domain-Driven DesignIntroduction to Domain-Driven Design
Introduction to Domain-Driven Design
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp concepts
 
Drupalcon cph
Drupalcon cphDrupalcon cph
Drupalcon cph
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
MicroProfile Devoxx.us
MicroProfile Devoxx.usMicroProfile Devoxx.us
MicroProfile Devoxx.us
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 

Mais de Corneil du Plessis

Sweet Streams (Are made of this)
Sweet Streams (Are made of this)Sweet Streams (Are made of this)
Sweet Streams (Are made of this)Corneil du Plessis
 
Cloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A WorkshopCloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A WorkshopCorneil du Plessis
 
Enhancements in Java 9 Streams
Enhancements in Java 9 StreamsEnhancements in Java 9 Streams
Enhancements in Java 9 StreamsCorneil du Plessis
 
Performance Comparison JVM Languages
Performance Comparison JVM LanguagesPerformance Comparison JVM Languages
Performance Comparison JVM LanguagesCorneil du Plessis
 
Microservices Patterns and Anti-Patterns
Microservices Patterns and Anti-PatternsMicroservices Patterns and Anti-Patterns
Microservices Patterns and Anti-PatternsCorneil du Plessis
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsCorneil du Plessis
 
Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Corneil du Plessis
 
Polyglot persistence with Spring Data
Polyglot persistence with Spring DataPolyglot persistence with Spring Data
Polyglot persistence with Spring DataCorneil du Plessis
 
Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forCorneil du Plessis
 

Mais de Corneil du Plessis (15)

Sweet Streams (Are made of this)
Sweet Streams (Are made of this)Sweet Streams (Are made of this)
Sweet Streams (Are made of this)
 
Cloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A WorkshopCloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
 
QueryDSL - Lightning Talk
QueryDSL - Lightning TalkQueryDSL - Lightning Talk
QueryDSL - Lightning Talk
 
Enhancements in Java 9 Streams
Enhancements in Java 9 StreamsEnhancements in Java 9 Streams
Enhancements in Java 9 Streams
 
Reactive Spring 5
Reactive Spring 5Reactive Spring 5
Reactive Spring 5
 
Empathic API-Design
Empathic API-DesignEmpathic API-Design
Empathic API-Design
 
Performance Comparison JVM Languages
Performance Comparison JVM LanguagesPerformance Comparison JVM Languages
Performance Comparison JVM Languages
 
Microservices Patterns and Anti-Patterns
Microservices Patterns and Anti-PatternsMicroservices Patterns and Anti-Patterns
Microservices Patterns and Anti-Patterns
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with Angularjs
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
 
Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!
 
Polyglot persistence with Spring Data
Polyglot persistence with Spring DataPolyglot persistence with Spring Data
Polyglot persistence with Spring Data
 
Data repositories
Data repositoriesData repositories
Data repositories
 
Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting for
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 

Último

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 value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Último (20)

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 value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
+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...
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Dependency Injection in Spring in 10min

  • 1. Dependency Injection with Spring in 10 minutes Corneil du Plessis corneil.duplessis@gmail.com @corneil
  • 2. Introduction ● Assumptions – You have some appreciation of component-oriented development – You have seen Java code – You have heard of the Spring Framework or Dependency Injection ● Take away – Some appreciation for benefits of dependency injection – Some understanding of how Spring supports dependency injection.
  • 3. What is Dependency Injection? ● Robert C Martin and Martin Fowler has written some of the best articles on the subject. ● Dependency Injection is also known as Inversion of Control or Dependency Inversion. ● DI is a specific form of IoC. ● When an object is composed the responsibility for composing the dependents of the object is not handled by the specific object. ● Modern applications uses one or more containers or frameworks to take care of DI. ● Examples are EJB container and Spring Framework. ● We will look at mechanisms provider by Spring Framework
  • 4. What is Spring Framework? ● The Spring Framework provides support for a large number of useful programming patterns. ● Patterns in questions are: – Singleton – Factory – Locator – Visitor
  • 5. DI – Best Practice ● Required unchanging dependencies via constructor. ● Assemble and fail early ● Be careful of the cost of DI frameworks. – Don't use to create Data Transfer Objects.
  • 6. DI – Sample Classes
  • 7. DI – Sample Objects
  • 8. DI – Code without DI public ProfileDataAccessComponent() throws NamingException, FileNotFoundException, IOException { super(); // In EJB or Web Container try { InitialContext ctx = new InitialContext(); dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/profile"); } catch(Throwable x) { // Assume we are not in container. } if(dataSource == null) { // Manual creation outside of container Properties props = new Properties(); File propFile = new File("db.properties"); props.load(new FileInputStream(propFile)); BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(props.getProperty("db.driver")); ds.setUsername(props.getProperty("db.username")); ds.setPassword(props.getProperty("db.password")); ds.setUrl(props.getProperty("db.url")); ds.setMaxActive(Integer.parseInt(props.getProperty("db.maxActive", "10"))); ds.setMaxIdle(Integer.parseInt(props.getProperty("db.maxIdle", "5"))); ds.setInitialSize(Integer.parseInt(props.getProperty("db.initialSize", "5"))); ds.setValidationQuery(props.getProperty("db.validationQuery", "SELECT 1")); dataSource = ds; } }
  • 9. DI – More Code public ProfileNotificationSender() throws NamingException { super(); InitialContext ctx = new InitialContext(); factory = (ConnectionFactory) ctx.lookup("java:comp/env/jms/queue/ConnectionFactory"); destination = (Destination) ctx.lookup("java:comp/env/jms/queue/Profile"); }
  • 10. DI – Spring Beans from XML <context:property-placeholder location="db.properties" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> </bean> <bean id="profileDAC" class="org.springframework.di.demo.ProfileDataAccessComponent"> <constructor-arg ref="dataSource" /> </bean>
  • 11. DI – Spring Beans from XML <jee:jndi-lookup id="destination" jndi-name="jms/queue/Profile" expected-type="javax.jms.Destination" /> <jee:jndi-lookup id="connectionFactory" jndi-name="jms/queue/ConnectionFactory" expected-type="javax.jms.ConnectionFactory" /> <bean id="notificationSender" class="org.springframework.di.demo.ProfileNotificationSender"> <constructor-arg ref="connectionFactory" /> <constructor-arg ref="destination" /> </bean> <bean id="profileService" class="org.springframework.di.demo.ProfileService"> <constructor-arg ref="profileDAC" /> <constructor-arg ref="notificationSender" /> </bean>
  • 12. DI – Spring Annotations Config <context:property-placeholder location="db.properties" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> </bean> <jee:jndi-lookup id="destination" jndi-name="jms/queue/Profile" expected-type="javax.jms.Destination" /> <jee:jndi-lookup id="connectionFactory" jndi-name="jms/queue/ConnectionFactory" expected-type="javax.jms.ConnectionFactory" /> <context:component-scan base-package="org.springframework.di.autowire" />
  • 13. DI – Spring Annotations Code @Autowired public ProfileNotificationSender(ConnectionFactory factory, Destination destination) { super(); this.factory = factory; this.destination = destination; } @Service("profileService") public class ProfileService implements ProfileInteface { private ProfileDataAccessInterface dataAccess; private ProfileNotificationInterface notification; @Autowired public ProfileService(ProfileDataAccessInterface dataAccess, ProfileNotificationInterface notification) { super(); this.dataAccess = dataAccess; this.notification = notification; }
  • 14. DI – Spring Java Config @Configuration public class AppConfig { @Autowired Environment env; @Bean public Destination destination() { JndiObjectFactoryBean bean = new JndiObjectFactoryBean(); bean.setJndiName("jms/queue/Profile"); bean.setExpectedType(Destination.class); return (Destination) bean.getObject(); } @Bean public ConnectionFactory connectionFactory() { JndiObjectFactoryBean bean = new JndiObjectFactoryBean(); bean.setJndiName("jms/queue/ConnectionFactory"); bean.setExpectedType(ConnectionFactory.class); return (ConnectionFactory) bean.getObject(); } }
  • 15. DI – Spring Java Config @Configuration @PropertySource("db.properties") public class AppConfig { @Autowired Environment env; @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("db.driver")); dataSource.setUrl(env.getProperty("db.url")); dataSource.setUsername(env.getProperty("db.username")); dataSource.setPassword(env.getProperty("db.password")); return dataSource; } }
  • 16. Questions ● Demo code at https://github.com/corneil/demos/tree/master/spring-di-sample ● Discuss on JUG Facebook https://www.facebook.com/groups/jozijug ● Discuss on JUG Meetup