• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar

JavaTutorOnline

Java Tutor Online

  • Home
  • Courses
  • Tutorials
    • Java
    • Servlets
    • Struts
    • Spring
    • Webservice
  • FAQ
  • Testimonials
  • Blog
  • Contact Us

Dependency Injection

Dependency Injection is a very popular Design pattern. It was earlier called Inversion of Control.
Explanation of Dependency Injection with an Example

Example.
The PersistenceManager class is used to persist objects to database

1
2
3
4
5
6
7
8
9
10
public class PersistenceManager
{
public void store(Object obj)
{
Contect ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup(“java:/comp/env/jdbc/myDataSource”);
Connection con=ds.getConnection()
 
}
}

 

In the above example we have hardcoded the jndi name . It is not that all application will use the same jndi name. According to Dependency injection design pattern dependency should be injected to the using component.Here a DataSource object should be passed to the PersistenceManager instead of forcing it to create.

1
2
3
4
5
6
7
8
9
10
11
12
public class PersistenceManager
{
private ce ds;
PersistenceManager(Datasource ds)
{
this.ds=ds;
}
public void store(Object object)
{
Connection con=ds.getConnection();
}
}

 

Now PersistenceManager is decoupled from DataSource so PersistenceManager becomes more reusuable

The User of the PersistenceManager class knows better what DataSource to use then the programmer. So the user will provide the DataSource instance whileusing the PersistenceManager.

DependencyInjection can used not only with constructor but also through setter methods in the PersistenceManager class.

Struts2 uses DependencyInjection to set the action properties with the request parameters.
So one won’t have to worry about populating the properties and can work on them present inside a method of the action.

Filed Under: Struts

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Mr Chinmay

Chinmay Patel
Online Java Tutor-Demo Class

Phone & Whatsapp +919853166385
[email protected]

Recent Posts

  • How to Learn Java in One day? | JavaTutorOnline
  • Constructor in Java and Overloaded Constructor Example Program
  • Important Interview Questions on Java Multithreading
  • React Spring Boot Web Services Integration
  • Spring Boot RESTful Web Services Example
  • Top Spring MVC Interview Questions and Answers for Developers
  • Top Spring Core Interview Questions and Answers for Developers
  • Host Java Web Apps for Free on Mobile with Tomcat and Termux
  • How to Deploy Java Web Application on Aws EC2 with Elastic IP
  • Simple Jsp Servlet Jdbc User Registration using Tomcat Mysql and Eclipse
Copyright © 2025 JavaTutorOnline