因為spring架構設計内容比較多,是以部落客分成三篇講解spring架構
- spring基礎篇一:Ioc控制反轉。DI依賴注入,整合junit
- spring基礎篇二: AOP切面程式設計,JDBCTemplate
- spring基礎篇三: 事務管理,SSM整合
1 Spring架構概述
1.1 什麼是spring
- 它是為了解決企業應用開發的複雜性而建立的。架構的主要優勢之一就是其分層架構,分層架構允許使用者選擇使用哪一個元件,同時為 J2EE 應用程式開發提供內建的架構。Spring使用基本的JavaBean來完成以前隻可能由EJB完成的事情。然而,Spring的用途不僅限于伺服器端的開發。從簡單性、可測試性和松耦合的角度而言,任何Java應用都可以從Spring中受益。Spring的核心是控制反轉(IoC)和面向切面(AOP)。
- 總結:spring是一個分層的javase.EE 一站式 輕量級 開源架構
- 量級:輕量級,與EJB相比,依賴資源少,銷毀資源少
- 分層:一站式。為每層都提供了解決方案
- web層:spring-MVC
- service層 :spring
- dao層:mybatis,jdbcTemplate–>Spring-data
1.2 spring核心
Spring的核心是控制反轉(IoC)和面向切面(AOP)
1.3 spring 優勢
友善解耦,簡化開發 (高内聚低耦合)
• Spring就是一個大工廠(容器),可以将所有對象建立和依賴關系維護,交給Spring管理
• spring工廠是用于生成bean
- AOP程式設計的支援
• Spring提供面向切面程式設計,可以友善的實作對程式進行權限攔截、運作監控等功能
- 聲明式事務的支援
• 隻需要通過配置就可以完成對事務的管理,而無需手動程式設計
- 友善程式的測試
• Spring對Junit4支援,可以通過注解友善的測試Spring程式
- 友善內建各種優秀架構
• Spring不排斥各種優秀的開源架構,其内部提供了對各種優秀架構(如:Struts、Hibernate、MyBatis、Quartz等)的直接支援
- 降低JavaEE API的使用難度
• Spring 對JavaEE開發中非常難用的一些API(JDBC、JavaMail、遠端調用等),都提供了封裝,使這些API應用難度大大降低
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2Lc1zZyo1bk1mW0gmMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DO5kjM0MTM5AzNykDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
2 入門案例 Ioc控制反轉
2.1導入jar包
- 4+1 :4個核心包(bean,core,context,expression)+ 1個依賴 (commons-loggins)
2.2目标類
- 提供userService的接口和實作類
- 獲得userService的實作類的執行個體
public interface UserService {
public void addUser();
}
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("a_ico add user");
}
}
之前開發中,直接new一個對象即可。
學習spring之後,将由Spring建立對象執行個體–> IoC 控制反轉(Inverse of Control)
之後需要執行個體對象時,從spring工廠(容器)中獲得,需要将實作類的全限定名稱配置到xml檔案中
2.3配置檔案
- 位置:任意,開發中一般在classpath下(src)
- 名稱:任意,開發中常用applicationContext.xml
-
下載下傳spring插件,添加beans的限制 或者 内容:添加schema限制
限制檔案位置:spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\ xsd-config.html
<?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">
<!-- 配置service
<bean> 配置需要建立的對象
id :用于之後從spring容器獲得執行個體時使用的
class :需要建立執行個體的全限定類名
-->
<bean id="userServiceId" class="com.itheima.a_ioc.UserServiceImpl"></bean>
</beans>
2.4 測試
@Test
public void demo02(){
//從spring容器獲得
//1 獲得容器
String xmlPath = "com/itheima/a_ioc/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//2獲得内容 --不需要自己new,都是從spring容器獲得
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
}
3 入門案例 DI
-
DI Dependency Injection ,依賴注入
is a :是一個,繼承。
has a:有一個,成員變量,依賴。
class B {
private A a; //B類依賴A類
}
依賴:一個對象需要使用另一個對象
注入:通過setter方法進行另一個對象執行個體設定。
- 例如:
class BookServiceImpl{ //之前開發:接口 = 實作類 (service和dao耦合) //private BookDao bookDao = new BookDaoImpl(); //spring之後 (解耦:service實作類使用dao接口,不知道具體的實作類) private BookDao bookDao; setter方法 }
模拟spring執行過程
建立service執行個體:BookService bookService = new BookServiceImpl() -->IoC
建立dao執行個體:BookDao bookDao = new BookDaoImple() -->IoC
将dao設定給service:bookService.setBookDao(bookDao); -->DI
3.1 目标類
- 建立BookService接口和實作類
- 建立BookDao接口和實作類
- 将dao和service配置 xml檔案
- 使用api測試
3.1.1 dao
public interface BookDao {
public void addBook();
}
public class BookDaoImpl implements BookDao {
@Override
public void addBook() {
System.out.println("di add book");
}
}
3.1.2
public interface BookService {
public abstract void addBook();
}
public class BookServiceImpl implements BookService {
// 方式1:之前,接口=實作類
// private BookDao bookDao = new BookDaoImpl();
// 方式2:接口 + setter
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook(){
this.bookDao.addBook();
}
}
3.2 配置檔案
3.3 測試
@Test
public void demo01(){
//從spring容器獲得
String xmlPath = "com/itheima/b_di/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
BookService bookService = (BookService) applicationContext.getBean("bookServiceId");
bookService.addBook();
}
4 4 myeclipse schema xml提示
-
步驟一:确定xsd檔案位置
spring-framework-3.2.0.RELEASE\schema\beans
spring架構基礎篇一 ——Ioc控制反轉,DI依賴注入1 Spring架構概述2 入門案例 Ioc控制反轉3 入門案例 DI4 4 myeclipse schema xml提示5 核心API6 裝配Bean 基于xml7 裝配Bean 基于注解 - 步驟二:複制路徑
spring架構基礎篇一 ——Ioc控制反轉,DI依賴注入1 Spring架構概述2 入門案例 Ioc控制反轉3 入門案例 DI4 4 myeclipse schema xml提示5 核心API6 裝配Bean 基于xml7 裝配Bean 基于注解 - 步驟三:搜尋“xml catalog”
- 步驟四:添加限制提示
spring架構基礎篇一 ——Ioc控制反轉,DI依賴注入1 Spring架構概述2 入門案例 Ioc控制反轉3 入門案例 DI4 4 myeclipse schema xml提示5 核心API6 裝配Bean 基于xml7 裝配Bean 基于注解
5 核心API
- 了解api
-
BeanFactory :這是一個工廠,用于生成任意bean。
采取延遲加載,第一次getBean時才會初始化Bean
- ApplicationContext:是BeanFactory的子接口,功能更強大。(國際化處理、事件傳遞、Bean自動裝配、各種不同應用層的Context實作)。當配置檔案被加載,就進行對象執行個體化。
-
ClassPathXmlApplicationContext 用于加載classpath(類路徑、src)下的xml
加載xml運作時位置 --> /WEB-INF/classes/…xml
-
FileSystemXmlApplicationContext 用于加載指定盤符下的xml
加載xml運作時位置 --> /WEB-INF/…xml
通過java web ServletContext.getRealPath() 獲得具體盤符
@Test
public void demo02(){
//使用BeanFactory --第一次條用getBean執行個體化
String xmlPath = "com/itheima/b_di/beans.xml";
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(xmlPath));
BookService bookService = (BookService) beanFactory.getBean("bookServiceId");
bookService.addBook();
}
6 裝配Bean 基于xml
6.1 執行個體化方式
- 3中bean執行個體化方式,預設構造,靜态工廠,執行個體工廠
6.1.1 預設構造
<bean id="" class=""> 必須提供預設構造
6.1.2 靜态工廠
- 常用與spring整合其他架構(工具)
- 靜态工廠:用于生成執行個體對象,所有的方法必須是static
<bean id="" class="工廠全限定類名" factory-method="靜态方法">
6.1.2.1 工廠
public class MyBeanFactory {
/**
* 建立執行個體
* @return
*/
public static UserService createService(){
return new UserServiceImpl();
}
}
6.1.2.2 spring配置
<!-- 将靜态工廠建立的執行個體交予spring
class 确定靜态工廠全限定類名
factory-method 确定靜态方法名
-->
<bean id="userServiceId" class="com.itheima.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>
6.1.3 執行個體工廠
- 執行個體工廠:必須先有工廠執行個體對象,通過執行個體對象建立對象。提供所有的方法都是“非靜态”的。
6.1.3.1 工廠
/**
* 執行個體工廠,所有方法非靜态
*
*/
public class MyBeanFactory {
/**
* 建立執行個體
* @return
*/
public UserService createService(){
return new UserServiceImpl();
}
}
6.1.3.2 spring配置
!-- 建立工廠執行個體 -->
<bean id="myBeanFactoryId" class="com.itheima.c_inject.c_factory.MyBeanFactory"></bean>
<!-- 獲得userservice
* factory-bean 确定工廠執行個體
* factory-method 确定普通方法
-->
<bean id="userServiceId" factory-bean="myBeanFactoryId" factory-method="createService"></bean>
6.2 Bean種類
- 普通bean:之前操作的都是普通bean。 ,spring直接建立A執行個體,并傳回
-
FactoryBean:是一個特殊的bean,具有工廠生成對象能力,隻能生成特定的對象。
bean必須使用 FactoryBean接口,此接口提供方法 getObject() 用于獲得特定bean。
先建立FB執行個體,使用調用getObject()方法,并傳回方法的傳回值
FB fb = new FB();
return fb.getObject();
-
BeanFactory 和 FactoryBean 對比?
BeanFactory:工廠,用于生成任意bean。
FactoryBean:特殊bean,用于生成另一個特定的bean。例如:ProxyFactoryBean ,此工廠bean用于生産代理。 獲得代理對象執行個體。AOP使用
6.3 作用域
- 作用域:用于确定spring建立bean執行個體個數
spring架構基礎篇一 ——Ioc控制反轉,DI依賴注入1 Spring架構概述2 入門案例 Ioc控制反轉3 入門案例 DI4 4 myeclipse schema xml提示5 核心API6 裝配Bean 基于xml7 裝配Bean 基于注解 -
取值:
singleton 單例,預設值。
prototype 多例,每執行一次getBean将獲得一個執行個體。例如:struts整合spring,配置action多例。
配置資訊
<bean id="" class="" scope="">
<bean id="userServiceId" class="com.itheima.d_scope.UserServiceImpl"
scope="prototype" ></bean>
6.4 生命周期
6.4.1 初始化和銷毀
- 目标方法執行前後執行後,将進行初始化或銷毀
<bean id="" class="" init-method="初始化方法名稱" destroy-method="銷毀的方法名稱">
6.4.1.1 目标類
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("e_lifecycle add user");
}
public void myInit(){
System.out.println("初始化");
}
public void myDestroy(){
System.out.println("銷毀");
}
}
6.4.1.2 spring配置
<!--
init-method 用于配置初始化方法,準備資料等
destroy-method 用于配置銷毀方法,清理資源等
-->
<bean id="userServiceId" class="com.itheima.e_lifecycle.UserServiceImpl"
init-method="myInit" destroy-method="myDestroy" ></bean>
6.4.1.3 測試
@Test
public void demo02() throws Exception{
//spring 工廠
String xmlPath = "com/itheima/e_lifecycle/beans.xml";
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
//要求:1.容器必須close,銷毀方法執行; 2.必須是單例的
// applicationContext.getClass().getMethod("close").invoke(applicationContext);
// * 此方法接口中沒有定義,實作類提供
applicationContext.close();
}
6.4.2 BeanPostProcessor 後處理bean
- spring 提供一種機制,隻要實作此接口BeanPostProcessor ,并将這個類提供給spring容器,spring容器将自動執行,在初始化方法之前執行before(),在初始化方法後執行after(),配置
- Factory hook(勾子) that allows for custom modification of new bean instances, e.g. checking for marker interfaces or wrapping them with proxies.
-
spring提供工廠勾子,用于修改執行個體對象,可以生成代理對象,是AOP底層。
模拟
A a =new A();
a = B.before(a) --> 将a的執行個體對象傳遞給後處理bean,可以生成代理對象并傳回。
a.init();
a = B.after(a);
a.addUser(); //生成代理對象,目的在目标方法前後執行(例如:開啟事務、送出事務)
a.destroy()
6.4.2.1 編寫 實作類
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("前方法 : " + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
System.out.println("後方法 : " + beanName);
// bean 目标對象
// 生成 jdk 代理
return Proxy.newProxyInstance(
MyBeanPostProcessor.class.getClassLoader(),
bean.getClass().getInterfaces(),
new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("------開啟事務");
//執行目标方法
Object obj = method.invoke(bean, args);
System.out.println("------送出事務");
return obj;
}});
}
}
6.4.2.2 配置
<!-- 将後處理的實作類注冊給spring -->
<bean class="com.itheima.e_lifecycle.MyBeanPostProcessor"></bean>
-
問題1:後處理bean作用某一個目标類,還是所有目标類?
所有
-
問題2:如何隻作用一個?
通過“參數2”beanName進行控制
6.5 屬性依賴注入
- 依賴注入方式:手動裝配 和 自動裝配
-
手動裝配:一般進行配置資訊都采用手動
基于xml裝配:構造方法、setter方法
基于注解裝配:
-
自動裝配:struts和spring 整合可以自動裝配
byType:按類型裝配
byName:按名稱裝配
constructor構造裝配,
auto: 不确定裝配。
6.5.1 構造方法
6.5.1.1 目标類
public class User {
private Integer uid;
private String username;
private Integer age;
public User(Integer uid, String username) {
super();
this.uid = uid;
this.username = username;
}
public User(String username, Integer age) {
super();
this.username = username;
this.age = age;
}
6.5.1.2 spring配置
<!-- 構造方法注入
* <constructor-arg> 用于配置構造方法一個參數argument
name :參數的名稱
value:設定普通資料
ref:引用資料,一般是另一個bean id值
index :參數的索引号,從0開始 。如果隻有索引,比對到了多個構造方法時,預設使用第一個。
type :确定參數類型
例如:使用名稱name
<constructor-arg name="username" value="jack"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
例如2:【類型type 和 索引 index】
<constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
<constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>
-->
<bean id="userId" class="com.itheima.f_xml.a_constructor.User" >
<constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
<constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>
</bean>
6.5.2 setter 方法
<!-- setter方法注入
* 普通資料
<property name="" value="值">
等效
<property name="">
<value>值
* 引用資料
<property name="" ref="另一個bean">
等效
<property name="">
<ref bean="另一個bean"/>
-->
<bean id="personId" class="com.itheima.f_xml.b_setter.Person">
<property name="pname" value="陽志"></property>
<property name="age">
<value>1234</value>
</property>
<property name="homeAddr" ref="homeAddrId"></property>
<property name="companyAddr">
<ref bean="companyAddrId"/>
</property>
</bean>
<bean id="homeAddrId" class="com.itheima.f_xml.b_setter.Address">
<property name="addr" value="阜南"></property>
<property name="tel" value="911"></property>
</bean>
<bean id="companyAddrId" class="com.itheima.f_xml.b_setter.Address">
<property name="addr" value="北京八寶山"></property>
<property name="tel" value="120"></property>
</bean>
6.5.3 P命名空間 {了解即可}
-
對“setter方法注入”進行簡化,替換,而是在
<bean p:屬性名=“普通值” p:屬性名-ref=“引用值”>
- p命名空間使用前提,必須添加命名空間
<bean id="personId" class="com.itheima.f_xml.c_p.Person"
p:pname="禹太璞" p:age="22"
p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId">
</bean>
<bean id="homeAddrId" class="com.itheima.f_xml.c_p.Address"
p:addr="DG" p:tel="東莞">
</bean>
<bean id="companyAddrId" class="com.itheima.f_xml.c_p.Address"
p:addr="DG" p:tel="島國">
</bean>
7 裝配Bean 基于注解
- 注解:就是一個類,使用@注解名稱
- 開發中:使用注解 取代 xml配置檔案。
-
@Component取代
@Component(“id”) 取代
2.web開發,提供3個@Component注解衍生注解(功能一樣)取代
@Repository :dao層
@Service:service層
@Controller:web層
3.依賴注入 ,給私有字段設定,也可以給setter方法設定
普通值:@Value("")
引用值:
方式1:按照【類型】注入
@Autowired
方式2:按照【名稱】注入1
@Autowired
@Qualifier(“名稱”)
方式3:按照【名稱】注入2
@Resource(“名稱”)
4.生命周期
初始化:@PostConstruct
銷毀:@PreDestroy
5.作用域
@Scope(“prototype”) 多例
- 注解使用前提,添加命名空間,讓spring掃描含有注解類
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 元件掃描,掃描含有注解的類 -->
<context:component-scan base-package="com.itheima.g_annotation.a_ioc"></context:component-scan>
</beans>