Spring開發
阿新 • • 發佈:2017-06-28
img odi 關心 環境 解耦 依賴屬性 pre 添加 接口與實現
沒有狀態變化的對象(無狀態對象):應當做成單例。
Spring-framework的下載:http://repo.spring.io/release/org/springframework/spring/。
配置Spring環境(Spring Context)所需要的jar包,以及它們之間的相互依賴關系:
Spring基礎配置:
- IoC容器:控制反轉(或者從另一個角度叫依賴註入)。
- AOP面向切面編程:分離橫切邏輯。
- 聲明式事務。
IoC容器 —— 控制反轉(容器接管對象的管理以及對象間的依賴關系) —— Xml配置(<beans>的名稱空間必須添加,不然會報錯,如下):
<?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="ctest" class="test.CTest"> <property name="value" value="10000" /> </bean> <bean id="mytest" class="test.MyTest"> <property name="it" ref="ctest" /> </bean> </beans>
IoC依賴註入 —— 通過容器,根據配置註入依賴屬性:
測試代碼:
beans(接口與實現):
//接口 package test; public interface ITest { publicvoid print(); } //接口實現 package test; public class CTest implements ITest { private int value; @Override public void print() { System.out.println(value); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } }
依賴註入 —— 獲取bean(有兩種方法):
package test; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { private static ApplicationContext context = null; //方法一:通過配置依賴關系,然後用getter、setter操作bean(這種方式只適用於static bean) //這裏就體現了IoC的解耦和,即依賴關系由IoC管理。 //分離了關註點:分開了,接口的實現和具體使用哪個接口的選擇,以及其使用無需在此關心接口采用的哪一個實現 private static ITest it = null; public ITest getIt() { return it; } public void setIt(ITest it) { this.it = it; } @BeforeClass public static void setUpBeforeClass() { System.out.println("hello"); context = new ClassPathXmlApplicationContext("app.xml"); } @AfterClass public static void tearDownAfterClass() { System.out.println("goodbye"); if(context instanceof ClassPathXmlApplicationContext) { ((ClassPathXmlApplicationContext) context).destroy(); } } /** * 測試獲取bean的第一種方法: */ @Test public void testOne() { it.print(); } /** * 測試第二種方法:getBean */ @Test public void testTwo() { //方法二:直接通過getBean方法,獲得某個bean // ITest itest = context.getBean(CTest.class); ITest itest = (ITest) context.getBean("ctest"); itest.print(); } }
AOP面向切面編程:
Spring開發