请通过简单的java类给我看一个依赖注入原理的小例子虽然我已经看过spring,但是如果我需要用简单的java类术语来解释它,那么请你通过一个简单的例子给我看。提前谢谢.
2 回答
When using dependency injection, you rely on the container to inject your objects dependencies instead of creating them yourself during execution. For example:
Without using dependency injection I would have to write something like this:
public class ATMTransferService {
private AccountDAO accountDAO;
public void transfer(Account from, Account to){
AccountDAO accountDAO = new AccountDAO();
...Code that transfers money from one account to another and saves it...
accountDAO.store();
}
Notice that I had to instantiate accountDAO myself, and the responsibility of getting my dependancies was handled by myself.
By using spring or some other framework that allows for DI, I would transfer that responsibility tothe container, by writing something like:
<bean id="ATMTransfer" class="com.example.ATMTransferService" >
<property name="accountDAO" ref="AccDAO" />
</bean>
<bean id="AccDAO" class="com.model.AccountDAO">
<property name="sessionFactory" ref="sessFac"
</bean>
<bean id="sessFac" class="..."
//Dependencies required for the cration fo session factory.
</bean>
Now my class would like like this: public class ATMTransferService { private AccountDAO accountDAO;
public void transfer(Account from, Account to){
...Code that transfers money from one account to another and saves it...
accountDAO.store();
}
In this case, I've ommited the AccountDAO class, but it would have a dependency on a SessionFactory. You could also use a pre-defined constructor instead of using the default constructor by specifying it on the xml configuration.
I hope i haven't simplified it too much, once the benefits of dependency injection are greater than this, you could swap implementation classes by just modifying an xml configuration for starters. You also get a much cleaner code once you remove dependency creation code from your business classes. It is really a great manner to promote interface oriented programming.
这篇文章有一个非常好的使用注解的基本 Java 示例
http://simplespringtutorial.com/annotations.html
这里通过简单的 Java 示例非常清楚地介绍了 DI 的基础知识