Spring是一個開源框架,Spring是于2003 年興起的一個輕量級的Java 開發(fā)框架,由Rod Johnson在其著作 Expert One-On-One J2EE Development and Design 中闡述的部分理念和原型衍生而來。它是為了解決企業(yè)應(yīng)用開發(fā)的復(fù)雜性而創(chuàng)建的??蚣艿闹饕獌?yōu)勢之一就是其分層架構(gòu),分層架構(gòu)允許使用者選擇使用哪一個組件,同時為 J2EE 應(yīng)用程序開發(fā)提供集成的框架。Spring 使用基本的 JavaBean來完成以前只可能由 EJB 完成的事情。然而,Spring 的用途不僅限于服務(wù)器端的開發(fā)。從簡單性、可測試性和松耦合的角度而言,任何 Java 應(yīng)用都可以從 Spring 中受益。Spring 的核心是控制反轉(zhuǎn)(IoC)和面向切面(AOP)。簡單來說,Spring 是一個分層的 JavaSE/EEfull-stack(一站式) 輕量級開源框架。
步驟一:下載Spring的開發(fā)包

步驟二:創(chuàng)建Web項目,引入Spring的開發(fā)包:

步驟三:引入相關(guān)配置文件:
- log4j.properties 可以自行配置
- Spring的配置文件applicationContext.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-4.2.xsd ">
</beans>
步驟四:編寫相關(guān)的類:
public class User {
private String name;
private Integer age;
public User() {
System.out.println("User對象空參構(gòu)造方法!!!!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
步驟五:完成配置
<?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-4.2.xsd ">
<!-- 將User對象交給spring容器管理 -->
<!-- Bean元素:使用該元素描述需要spring容器管理的對象
class屬性:被管理對象的完整類名.
name屬性:給被管理的對象起個名字.獲得對象時根據(jù)該名稱獲得對象.
可以重復(fù).可以使用特殊字符.
id屬性: 與name屬性一模一樣.
名稱不可重復(fù).不能使用特殊字符.
結(jié)論: 盡量使用name屬性.
-->
<bean name="user" class="cn.itcast.bean.User" ></bean>
</beans>
步驟六:編寫測試程序:
public class Demo {
@Test
public void fun1(){
//1 創(chuàng)建容器對象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2 向容器"要"user對象"
User u = (User) ac.getBean("user");
}
}
運行JUnit測試:
User對象空參構(gòu)造方法!!!!