• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
Online Java Training-Online Java Tutor-Private Java Classes

Online Java Training-Online Java Tutor-Private Java Classes

Personal Online Java Training through Skype

  • 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

Phone & Whatsapp +919853166385
[email protected]
Skype id: p.chinmay

Recent Posts

  • How to Learn Java in One day ? | JavaTutorOnline
  • Simple Jsp Servlet Jdbc User Registration using Tomcat Mysql and Eclipse
  • How to learn Java Programming Language the Best way ? | JavaTutorOnline
  • Recursion in Java Example Program | Understanding Java Recursion
  • Important Core Java Interview Questions and Answers
  • How to Create Threads in Java | Multithreading in Java | JavaTutorOnline
  • Why Multiple Inheritance in Java not supported?
  • A Simple Spring Mvc Hello World Example | Spring Mvc Tutorial
  • How to become a good Teacher |Ideal Teacher | Perfect Teacher
  • OGNL in Struts 2 Tutorial | JavaTutorOnline
Copyright © 2022 JavaTutorOnline