IDEA創建Spring實例比較簡單,
1.直接選擇創建Spring項目即可,會自動下載所需包。
2.src下創建所需文件
1.Person類
package com.bird.service;
import com.bird.service.PersonServer;
/**
* Created by Administrator on 2017/7/13.
*/
public class PersonServerImp implements PersonServer{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public void save() {
System.out.println("name:"+getName()+"age:"+getAge());
}
}
2.測試類test
package com.bird.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by Administrator on 2017/7/13.
*/
public class test {
public static void main(String[] args){
ApplicationContext apc = new ClassPathXmlApplicationContext("beans.xml");
PersonServerImp p = (PersonServerImp)apc.getBean("personService");
p.save();
}
}
3.beans.xml,這個文件名可自己設置,在 ApplicationContext apc = new ClassPathXmlApplicationContext("beans.xml");方法里對應。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="personService" class="com.bird.service.PersonServerImp">
<property name="name" value="xiaoyue"/>
<property name="age" value="25"/>
</bean>
</beans>
4.運行
這就是所謂的控制反轉/依賴注入...
控制反轉意思就是說,當我們調用一個方法或者類時,不再有我們主動去創建這個類的對象,控制權交給別人(spring)。
依賴注入意思就是說,spring主動創建被調用類的對象,然后把這個對象注入到我們自己的類中,使得我們可以使用它。