Advantages of Dependency Injection

Advantages of Dependency Injection

Loosely coupled:
Dependency injection gives the opportunities to eliminate hard-coded object creation – which is hard to manage or modify, But in DI if you need to change method signatures or any other changes then no need to go into code for required changes, simply change in central configuration files.  In case of non DI app, all dependent types for the objects in the instantiation process (factory) must have to be known at compile time but in DI it happens on run-time.

Separation of responsibility:
It separates total dependency management from the code. This is like – “who will do what” .  Code will be written to implement functionality and dependency is managed by spring IOC container, which uses only configuration file and provides full life-cycle management.

Separate configuration from code:
It gives more readability, no dependency related code inside class like object creation, all are specified on configuration. To understand an existing project flow, simply go through the configuration files – you can understand the basic project flow or overview of the project.

Easy Testing with mock objects:
While using dependency injection, dependencies can be easily injected into a Bean, like injecting a mock implementations of a Beans dependencies. Mock objects are used for testing(to create mock objects) as it gives the real implementation of a Bean dynamically. You can use Mockito, EasyMock etc. for creating mock objects.

Below example uses easyMock as a mocking framework and unit test made easy.

@RunWith(UnitilsJUnit4TestClassRunner.class)
public class MockingAccountServiceWithEasyMockTest {

/** The object to test */
private AccountService instance;

/**
* EasyMock creates the mock object
*/
@Mock
private AccountDao accmockDao;

@Before
public void setUp() throws Exception {
/* Create the AccountService object to test */
instance = new AccountService();
}

@Test
public void testFindAddressWithEasyMock() {

/* Inject the mock dependency */
instance.setAccountDao(accmockDao);

//CODE BLOCK

/* Run the test */
instance.findAccount(id);

/* Verify results */
verifyResults();
}
}

Gopal Das
Follow me

1 Comment

  1. when to use aspectj annotation based aop and when to use spring aop
    which is better and why?

    also i want to know what is load time weaving ,compile time weaving and run time weaving
    what are the differences between them.

Leave a Reply to rahul Cancel reply

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