struts 是 web 架構 (jsp/action/actionfrom)
hibernate 是 orm(對象關系映射) 架構 , 處于持久層 .
spring 是容器架構 , 用于配置 bean (service/dao/domain/action/ 資料源 ) , 并維護 bean 之間關系的架構
model層:業務層+dao層+持久層
service類:
package com.service;
public class UserService {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayHello(){
System.out.println("你好:"+name);
}
}
applicationContext.xml檔案:
<!-- bean 元素的作用是,當我們的 spring 架構加載時候, spring 就會自動的建立一個 bean 對象,并放入記憶體
UserService userSerivce=new UserService();
userSerivce.setName(" 張三 ");
當ClassPathXmlApplicationContext("applicationContext.xml");執行的時候,我們的spring容器對象被建立,同時
applicaionContext.xml中配置的bean就會被建立(記憶體[Hashmap/HashTable])
-->
<bean id="userservice" class="com.service.UserService">
<property name="name">
<value> 張三 </value>
</property>
</bean>
測試類:
//UserService userService=new UserService();
//userService.setName("chenzheng");
//userService.sayHello();
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService=(UserService) ac.getBean(" userservice ");
userService.sayHello();
spring 是一個容器架構,可以配置各種 bean(action/service/domain/dao), 并且可以維護 bean 與 bean 的關系 , 當我們需要使用某個 bean 的時候,可以 使用 getBean(id) 即可 .
ioc(inverse of controll ) 控制反轉 : 所謂控制反轉就是把建立對象 (bean), 和維護對象 (bean) 的關系的權利從程式中轉移到 spring 的容器 (applicationContext.xml), 而程式本身不再維護 .
di(dependency injection) 依賴注入 : 實際上 di 和 ioc 是同一個概念, spring 設計者認為 di 更準确表示 spring 核心技術
建立工具類ApplicaionContextUtil.java:
package com.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
final public class ApplicaionContextUtil {
private static ApplicationContext ac=null;
private ApplicaionContextUtil(){
}
static{
ac=new ClassPathXmlApplicationContext("applicationContext.xml");
}
public static ApplicationContext getApplicationContext(){
return ac;
}
}
測試類可改為:
((UserService)ApplicaionContextUtil.getApplicationContext().getBean("userservice")).sayHello();