Spring是一個類的容器實例化託管框架,可以實現對實現類的實例化進行動態的託管。更可以實現控制反轉。控制
反轉就是應用本身不負責倚賴對象的創建和維護,倚賴對象的創建和維護是通過其他的外部容器負責的,這樣的控制
權就由應用轉移到了容器。控制權的轉移就是所謂的反轉。
首先下載下來spring的壓縮包,在解壓後的dist文件夾下
面有spring.jar和commons-logging.jar這兩個JAR包(spring2.x的配置方法),這就是實現最簡單的spring框架所必須的包,然後就是
在docs/reference下面的參考手冊,裏面又spring的配置文件寫法。導入包完成後,最好在src目錄下面建立beans.xml配
置。
1、導入需要的包:
不像 Spring2.x版本 直接導入 dist目錄下面的Spring.jar即可,3.x開始jar包分開了。
需要導入的Jar包列表
2、配置、測試:
[java] view plaincopyprint?
<?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-2.5.xsd">
<bean id="personService" class="com.bird.service.impl.PersonServerImpl"></bean>
</beans>
然後寫一個類和抽取出接口
package com.bird.service;
public interface PersonServer {
void save();
}
package com.bird.service.impl;
import com.bird.service.PersonServer;
public class PersonServerImpl implements PersonServer {
@Override
public void save(){
System.out.println("save()方法調用");
}
}
然後在beans.xml中配置這個類就可以使用spring實例化這個類了,下面的操作全部都是面向接口的編程了。
package junit.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bird.service.PersonServer;
public class SpringTest {
@Test
public void test(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonServer s = (PersonServer)ctx.getBean("personService");
s.save();
}
}