本博文圍繞三點展開:
1:Spring 是什麼
Spring 是一個開源框架.
Spring 爲簡化企業級應用開發而生. 使用 Spring 可以使簡單的 JavaBean 實現以前只有 EJB 才能實現的功能.
Spring 是一個 IOC(DI) 和 AOP 容器框架.
具體描述 Spring:
輕量級:Spring 是非侵入性的 - 基於 Spring 開發的應用中的對象可以不依賴於 Spring 的 API
依賴注入(DI --- dependency injection、IOC)
面向切面編程(AOP --- aspect oriented programming)
容器: Spring 是一個容器, 因爲它包含並且管理應用對象的生命週期
框架: Spring 實現了使用簡單的組件配置組合成一個複雜的應用. 在 Spring 中可以使用 XML 和 Java 註解組合這些對象
一站式:在 IOC 和 AOP 的基礎上可以整合各種企業應用的開源框架和優秀的第三方類庫 (實際上 Spring 自身也提供了展現層的 SpringMVC 和 持久層的 Spring JDBC)
圖解:
2:搭建 Spring 開發環境
把以下 jar 包加入到工程的 classpath 下:
commons-logging-1.1.1.jar,spring-beans-4.0.0.RELEASE.jar,spring-context-4.0.0.RELEASE.jar,spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jarSpring 的配置文件: 一個典型的 Spring 項目需要創建一個或多個 Bean 配置文件, 這些配置文件用於在 Spring IOC 容器裏配置 Bean. Bean 的配置文件可以放在 classpath 下,也可以放在其它目錄下.
3:helloSpring:Demo
3.1編寫bean類,TestBean.java:
public class HelloSpring
{
private String name;
/**
* 設置 name
* @param 對name進行賦值
*/
public void setName(String name)
{
this.name = name;
}
public void hello()
{
System.out.println("hello "+name);
}
}
3.2編寫配置文件applicationContext.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"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置bean -->
<bean id="testBean" class="com.cgc.spring.beans.TestBean">
<property name="name" value="Spring"></property>
</bean>
</beans>
3.3編寫Mian類中main方法
public static void main(String[] args)
{
//1:創建Spring 的IOC容器對象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2:從IOC容器中獲取Bean實例
HelloSpring hello = (HelloSpring)ctx.getBean("helloSpring");
hello.hello();
}