環境:IntelliJ 14 ; jdk1.8
?
Spring操作步驟
1.新建項目---Spring Batch2.IntelliJ會自動加載jar包3.現在就可以在src目錄下寫Java類文件了4.將相應的類部署在XML配置文件spring-config.xml中 (Eclipse需要手動創建,貌似名為bean.xml)5.寫主程序main (右鍵-->Run)
HelloWord小程序
此處直接從第3步開始
3.首先定義兩個接口,Person和Axe
public interface Person {public void useAxe();
}
public interface Axe {public String chop();
}
然后定義接口的實現類,Chinese和StoneAxe
public class Chinese implements Person {private Axe axe;//設值注入public void setAxe(Axe axe) {this.axe = axe;}@Overridepublic void useAxe() {System.out.println(axe.chop());}
}
public class StoneAxe implements Axe {@Overridepublic String chop() {return "石斧砍柴好慢";}
}
4.修改spring-config.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="chinese" class="org.spring.service.impl.Chinese"><property name="axe" ref="stoneAxe"/></bean><bean id="stoneAxe" class="org.spring.service.impl.StoneAxe"/>
</beans>
5.寫主程序main
public class SpringTest {public static void main(String[] args){ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");Person p = (Person) ctx.getBean("chinese", Person.class);p.useAxe();}
}
程序到此結束,運行結果為:
石斧砍柴好慢
Spring的核心機制:依賴注入(Dependency Inhection)(控制反轉IoC—Inversion of Control)
依賴注入通常包括以下兩種:
設值注入:使用屬性的setter方法來注入被依賴的實例
構造注入:使用構造器來注入被依賴的實例
請看下面的例子
public class Chinese implements Person {private Axe axe;//設值注入public void setAxe(Axe axe) {this.axe = axe;}//構造注入public Chinese(Axe axe) {this.axe = axe;}@Overridepublic void useAxe() {System.out.println(axe.chop());}
}
不同的注入方式在配置文件中的配置也不一樣
<!--設值注入-->
<bean id="chinese" class="org.spring.service.impl.Chinese"><property name="axe" ref="steelAxe"/>
</bean>
<!--構造注入-->
<bean id="chinese" class="org.spring.service.impl.Chinese"><constructor-arg ref="stoneAxe"/>
</bean>
建議采用以設值注入為主,構造注入為輔的注入策略。對于依賴關系無需變化的注入,盡量采用構造注入;而其他的依賴關系的注入,則考慮使用設值注入。
?
Spring的兩個核心接口Spring容器最基本的接口是BeanFactory。它有一個子接口:ApplicationContext。
ApplicationContext有兩個常用的實現類:
FileSystemXmlApplicationContext:以基于文件系統的XML配置文件創建實例
ClassPathXmlApplicationContext:以類加載路徑下的XML配置文件創建實例