Spring框架的核心技術是IOC(控制反轉,也稱依賴注入)和AOP(面向切面編程)
Spring框架的作用:
Spring框架主要用於與其他技術進行整合,可將程序中的Bean組件實現低耦合關聯,最終可以提高系統擴展和維護性
Spring框架的優點:
獨立於各種應用服務器上
Spring的DI容器降低了業務對象替換的複雜性,提高了組件之間的解耦
Spring的AOP爲程序代碼提供了很好的代碼複用
Spring提供了與多種開發框架的良好整合
Spring框架是侵入性最少的的框架性框架
運用Spring框架的例子如下:設值注入
Test文件:
public class TestAxe {
public static void main(String[]args){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
IUseAxe iuseAxe = applicationContext.getBean("useAxeImpl", UseAxeImpl.class);
iuseAxe.useAxe();
}
}
2個實現類的接口:
public interface IAxe {
public void chop();
}
實現類:
public class SteelAxeImpl implements IAxe {
public void chop(){
System.out.println("這是把好用的金斧頭");
}
}
實現類:
public class StoneAxeImpl implements IAxe{
public void chop(){
System.out.println("這把銀斧頭挺好用的");
}
}
服務類(這裏指使用斧頭的服務類):
public interface IUseAxe {
//使用斧頭
public void useAxe();
}
public class UseAxeImpl implements IUseAxe {
private IAxe axe;
public void useAxe(){
axe.chop();
}
public IAxe getAxe() {
return axe;
}
public void setAxe(IAxe axe) {
this.axe = axe;
}
}
bean.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 定義金斧頭 -->
<bean id="steelAxeImpl" class="com.bean.service.SteelAxeImpl"></bean>
<!-- 定義銀斧頭 -->
<bean id="stoneAxeImpl" class="com.bean.service.StoneAxeImpl"></bean>
<!-- 使用哪種斧頭 -->
<bean id="useAxeImpl" class="com.bean.service.UseAxeImpl">
<property name="axe" ref="stoneAxeImpl"></property>
</bean>
</beans>
最後輸出結果:
這把銀斧頭挺好用的