What is Dependency Injection
Dependency injection is an approach to use external reference without any dependency. Each project has several modules that referenced with each other. When developer changes something ( even if atomic changes), all project will be affected with them and some problems will be occurred. So we want to remove dependency from each other.Let’s learn it with this example.
public interface UserDao {
boolean login(String username, String password);
}
public class UserDaoImpl implements UserDao {
@Override
public boolean login(String username, String password) {
return ( username.equals("test") && password.equals("test"));
}
}
How we use this. Here:
public class TestApplication {
public static void main(String[] args) {
UserDao user = new UserDaoImpl();
boolean isLogin = user.login("demo","password");
}
}
It is not important what we wrote at implementation. So we can write test objects easily. This approach is manual DI. There are several frameworks. Spring is one of them.Here is a configuration file and main class.
public class TestApplication {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"META-INF/beans.xml");
BeanFactory factory = context;
UsrDao user = (UserDao) factory.getBean("userDao");
boolean isLogin = user.login("demo","password");
}
}
About the IOC then, I’ll write more.
No related posts.
Trackbacks & Pingbacks