SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingSelcen Ozturkcan
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

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