Spring Dependency Injection and Inversion of Control

Take a look at the picture below:

The traditional way is to actively create; for example you see a juice described as follows:

public class MakeOrange {

	private String water;
	private String sugar;
	private String orange;

You want to drink this juice after seeing the description, then you proactively find a production machine, and then you bring it over,

public class Orange {
	private MakeOrange ora;
	public MakeOrange getOra() {
		return ora;
	}
	public void setOra(MakeOrange ora) {
		this.ora = ora;
	}
	public String Oranger(){
		String drinks="This is a drink composed of "+ora.getWater()+", "+ora.getSugar()+", "+ora.getOrange()+"!";
		return drinks;
	}
}

Then you start making juice:

public String makedrinks(){
		Orange ora=new Orange();
		return ora.Oranger();
	}

In order to drink juice, you have to create a production method yourself. Isn't this too troublesome; then why don't we find a third party to give us juice directly?

   <bean id="makeorange" class="pojo.MakeOrange">
   		<property name="water" value="水"></property>
   		<property name="sugar" value="糖"></property>
   		<property name="orange" value="橙汁"></property>
   </bean>
   <bean id="orange" class="pojo.Orange">
   		<property name="ora" ref="makeorange"></property>
   </bean>
BeanFactory ctx = new ClassPathXmlApplicationContext("spring.xml");
		Orange bean = (Orange) ctx.getBean("orange");
		String orange tree = bean. Orange tree();

This is passive creation. The third party passes what we want to the factory and the factory creates our juice for us. How he created it, you are not involved, it has nothing to do with you, you just said what you want, Then they give it to you; the third party here is the Spring container.

During this process:

1) The factory relies on the juice description you provide, that is, it must rely on the resources you provide to produce the juice you want, and then rely on the container to inject the resources it needs. This is dependency injection;

2) Inversion of control is to look at this process from the perspective of the container. The factory needs your resources, and then the container gives it your resources; the control is no longer in your hands.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521998&siteId=291194637