做者:Java架構研究室html
原文連接:mp.weixin.qq.com/s?__biz=MzU…java
Spring簡介 Spring 是一個開源框架,是一個分層的 JavaEE 一站式框架。mysql
所謂一站式框架是指 Spring 有 JavaEE 開發的每一層解決方案。web
WEB層:SpringMVCspring
Service層:Spring的Bean管理,聲明式事務sql
DAO層:Spring的JDBC模板,ORM模板數據庫
優勢:express
IOC:方便解耦合編程
AOP:對程序進行擴展瀏覽器
輕量級框架
方便與其餘框架整合
Spring使用 Spring開發包解壓後的目錄介紹:
docs: Spring 開發規範和API
libs: Spring jar 包和源代碼
schema: Spring 配置文件的約束
打開UC瀏覽器 查看更多精彩圖片
DataAccess 用於數據訪問,WEB 用於頁面顯示,核心容器也就是IOC部分。
控制反轉(IOC) 控制反轉(Inversion of Control)是指將對象的建立權反轉(交給)Spring。
使用IOC就須要導入IOC相關的包,也就是上圖中核心容器中的幾個包:beans,context,core,expression四個包。
實現原理 傳統方式建立對象:
UserDAO userDAO=new UserDAO();
進一步面向接口編程,能夠多態:
UserDAO userDAO=new UserDAOImpl();
這種方式的缺點是接口和實現類高耦合,切換底層實現類時,須要修改源代碼。程序設計應該知足OCP元祖,在儘可能不修改程序源代碼的基礎上對程序進行擴展。此時,可使用工廠模式:
class BeanFactory{
public static UserDAO getUserDAO(){
return new UserDAOImpl();
}
}
此種方式雖然在接口和實現類之間沒有耦合,可是接口和工廠之間存在耦合。
使用工廠+反射+配置文件的方式,實現解耦,這也是 Spring 框架 IOC 的底層實現。
//xml配置文件
//
class BeanFactory{
public static Object getBean(String id){
//解析XML
//反射
Class clazz=Class.forName();
return clazz.newInstance();
}
}
IOC XML 開發 在 docs 文件中包含了 xsd-configuration.hmtl 文件。其中定義了 beans schema。
<beans xmlns="www.springframework.org/schema/bean…"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xsi:schemaLocation="
www.springframework.org/schema/bean… www.springframework.org/schema/bean…">
//在此配置bean
調用類:
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService=(UserService)applicationContext.getBean("userService");
userService.save();
IOC 和 DI DI 指依賴注入,其前提是必須有 IOC 的環境,Spring 管理這個類的時候將類的依賴的屬性注入進來。
例如,在UserServiceImpl.java中:
public class UserServiceImpl implements UserService{
private String name;
public void setName(String name){
this.name=name;
}
public void save(){
System.out.println("save "+name);
}
}
在配置文件中:
<beans xmlns="www.springframework.org/schema/bean…"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xsi:schemaLocation="
www.springframework.org/schema/bean… www.springframework.org/schema/bean…">
測試代碼:
@Test
public void demo2(){
//建立Spring工廠
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService=(UserService)applicationContext.getBean("userService");
userService.save();
}
運行結果:
save tony
能夠看到,在配置文件中配置的屬性,在 Spring 管理該類的時候將其依賴的屬性成功進行了設置。若是不使用依賴注入,則沒法使用接口,只能使用實現類來進行設置,由於接口中沒有該屬性。
Spring 的工廠類 BeanFactory: 老版本的工廠類,在調用getBean()方法時,纔會生成類的實例。
ApplicationContext: 在加載配置文件的時候,就會將 Spring 管理的類都實例化。有兩個實現類:
ClassPathXmlApplicationContext: 加載類路徑下的配置文件
FileSystemXmlApplicationContext: 加載磁盤下的配置文件
bean標籤配置 id: 惟一約束,不能出現特殊字符
name: 理論上能夠重複,可是開發中最好不要。能夠出現特殊字符
生命週期:
init-method: bean被初始化的時候執行的方法
destroy-method: bean被銷燬的時候執行的方法
做用範圍:
scope: bean的做用範圍,有以下幾種,經常使用的是前兩種
singleton: 默認使用單例模式建立
prototype: 多例
request: 在web項目中,spring 建立類後,將其存入到 request 範圍中
session: 在web項目中,spring 建立類後,將其存入到 session 範圍中
globalsession: 在web項目中,必須用在 porlet 環境
屬性注入設置 構造方法方式的屬性注入: Car 類在構造方法中有兩個屬性,分別爲 name 和 price。
set 方法屬性注入: Employee 類在有兩個 set 方法,分別設置普通類型的 name 和引用類型的 Car (使用 ref 指向引用類型的 id 或 name)。
P名稱空間的屬性注入: 首先須要引入p名稱空間:
<beans xmlns="www.springframework.org/schema/bean…"
//引入p名稱空間
xmlns:p="www.springframework.org/schema/p"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xsi:schemaLocation="
www.springframework.org/schema/bean… www.springframework.org/schema/bean…">
若是是普通屬性:
若是是引用類型:
<bean id="employee" class="demo.Employee" p:name="xiaoming" p:car-ref:"car">
SpEL(Spring Expression Language)屬性注入(Spring 3.x以上版本)
集合類型屬性注入:
qirui
baoma
benchi
多模塊開發配置 在加載配置文件的時候,加載多個配置文件
在一個配置文件中引入多個配置文件,經過實現
IOC 註解開發 示例 引入jar包: 除了要引入上述的四個包以外,還須要引入aop包。
建立 applicationContext.xml ,使用註解開發引入 context 約束(xsd-configuration.html)
<beans xmlns="www.springframework.org/schema/bean…"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xmlns:context="www.springframework.org/schema/cont…" xsi:schemaLocation="
www.springframework.org/schema/bean… www.springframework.org/schema/bean…
www.springframework.org/schema/cont… www.springframework.org/schema/cont…">
組件掃描: 使用IOC註解開發,須要配置組件掃描,也就是哪些包下的類使用IOC的註解。
<context:component-scan base-package="demo1">
在類上添加註解
使用註解設置屬性的值
屬性若是有set方法,將屬性注入的註解添加到set方法
屬性沒有set方法,將註解添加到屬性上。
@Component("UserDao")//至關於配置了一個 其id爲UserDao,對應的類爲該類
public class UserDAOImpl implements UserDAO {
@Override
public void save() {
// TODO Auto-generated method stub
System.out.println("save");
}
}
註解詳解 @Component 組件註解,用於修飾一個類,將這個類交給 Spring 管理。
有三個衍生的註解,功能相似,也用來修飾類。
@Controller:修飾 web 層類
@Service:修飾 service 層類
@Repository:修飾 dao 層類
2.屬性注入 普通屬性使用 @Value 來設置屬性的值
對象屬性使用 @Autowired ,這個註解是按照類型來進行屬性注入的。若是但願按照 bean 的名稱或id進行屬性注入,須要用 @Autowired 和 @Qualifier 一塊兒使用
實際開發中,使用 @Resource(name=" ") 來進行按照對象的名稱完成屬性注入
3.其餘註解 @PostConstruct 至關於 init-method,用於初始化函數的註解
@PreDestroy 至關於 destroy-method,用於銷燬函數的註解
@Scope 做用範圍的註解,經常使用的是默認單例,還有多例 @Scope("prototype")
IOC 的 XML 和註解開發比較 適用場景:XML 適用於任何場景;註解只適合本身寫的類,不是本身提供的類沒法添加註解。
可使用 XML 管理 bean,使用註解來進行屬性注入
AOP開發 AOP 是 Aspect Oriented Programming 的縮寫,意爲面向切面編程,經過預編譯方式和運行期動態代理實現程序功能的統一維護的一種技術,是OOP的延續。
AOP 可以對程序進行加強,在不修改源碼的狀況下,能夠進行權限校驗,日誌記錄,性能監控,事務控制等。
也就是說功能分爲兩大類,一類是核心業務功能,一類是輔助加強功能。兩類功能彼此獨立進行開發。好比登陸功能是核心業務功能,日誌功能是輔助加強功能,若是有須要,將日誌和登陸編制在一塊兒。輔助功能就稱爲切面,這種能選擇性的、低耦合的把切面和核心業務功能結合的編程思想稱爲切面編程。
底層實現 JDK 動態代理只能對實現了接口的類產生代理。Cglib 動態代理能夠對沒有實現接口的類產生代理對象,生成的是子類對象。
使用 JDK 動態代理:
public interface UserDao {
public void insert();
public void delete();
public void update();
public void query();
}
實現類:
public class UserDaoImpl implements UserDao { @Override public void insert() { System.out.println("insert"); } @Override public void delete() { System.out.println("delete"); } @Override public void update() { System.out.println("update"); } @Override public void query() { System.out.println("query"); } }
JDK 代理:
public class JDKProxy implements InvocationHandler{
private UserDao userDao;
public JDKProxy(UserDao userDao){
this.userDao=userDao;
}
public UserDao createProxy(){
UserDao userDaoProxy=(UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
userDao.getClass().getInterfaces(), this);
return userDaoProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("update".equals(method.getName())){
System.out.println("權限校驗");
return method.invoke(userDao, args);
}
return method.invoke(userDao, args);
}
}
經過動態代理加強了 update 函數。 測試類:
public class Demo1 {
@Test
public void demo1(){
UserDao userDao=new UserDaoImpl();
UserDao proxy=new JDKProxy(userDao).createProxy();
proxy.insert();
proxy.delete();
proxy.update();
proxy.query();
}
}
運行結果爲:
insert
delete
權限校驗
update
query
CglibCglib 是第三方開源代碼生成類庫,能夠動態添加類的屬性和方法。
與上邊JDK代理不一樣,Cglib的使用方式以下:
public class CglibProxy implements MethodInterceptor{
//傳入加強的對象
private UserDao customerDao;
public CglibProxy(UserDao userDao){
this.userDao=userDao;
}
public UserDao createProxy(){
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(userDao.getClass());
enhancer.setCallback(this);
UserDao proxy=(UserDao)enhancer.create();
return proxy;
}
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
if("save".equals(method.getName())){
System.out.println("enhance function");
return methodProxy.invokeSuper(proxy, args);
}
return methodProxy.invokeSuper(proxy, args);
}
}
若是實現了接口的類,底層採用JDK代理。若是不是實現了接口的類,底層採用 Cglib代理。
IOC與傳統方式的比較 獲取對象方式:傳統經過 new 關鍵字主動建立一個對象。IOC 方式中,將對象的生命週期交給 Spring 管理,直接從 Spring 獲取對象。也就是控制反轉————將控制權從本身手中交到了 Spring 手中。
Spring 的 AOP 開發(AspectJ 的 XML 方式) AspectJ 是一個 AOP 的框架,Spring 引入 AspectJ,基於 AspectJ 進行 AOP 的開發。
相關術語 Joinpoint: 鏈接點,能夠被攔截到的點。也就是能夠被加強的方法都是鏈接點。
Pointcut: 切入點,真正被攔截到的點,也就是真正被加強的方法
Advice: 通知,方法層面的加強。對某個方法進行加強的方法,好比對 save 方法進行權限校驗,權限校驗的方法稱爲通知。
Introduction: 引介,類層面的加強。
Target: 目標,被加強的對象(類)。
Weaving: 織入,將 advice 應用到 target 的過程。
Proxy: 代理對象,被加強的對象。
Aspect: 切面,多個通知和多個切入點的組合。
使用方法 引入相關包
引入配置文件
<beans xmlns="www.springframework.org/schema/bean…"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xmlns:aop="www.springframework.org/schema/aop" xsi:schemaLocation="
www.springframework.org/schema/bean… www.springframework.org/schema/bean…
www.springframework.org/schema/aop www.springframework.org/schema/aop/…">
編寫目標類並配置:
public class ProductDaoImpl implements ProductDao {
@Override
public void save() {
System.out.println("save");
}
@Override
public void update() {
System.out.println("update");
}
@Override
public void find() {
System.out.println("find");
}
@Override
public void delete() {
System.out.println("delete");
}
}
編寫切面類,假設用於權限驗證並配置
public class MyAspectXML {
public void checkPri(){
System.out.println("check auth");
}
}
經過AOP配置完成對目標類的加強
<aop:pointcut expression="execution(* demo1.ProductDaoImpl.save(..))" id="pointcut1"/>
<aop:aspect ref="myAspect">
<aop:before method="chechPri" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
通知類型 前置通知:在目標方法執行前操做,能夠得到切入點信息
<aop:before method="chechPri" pointcut-ref="pointcut1"/>
public void checkPri(JoinPoint joinPoint){
System.out.println("check auth "+joinPoint);
}
後置通知:在目標方法執行後操做,能夠得到方法返回值
<aop:after-returning method="writeLog" pointcut-ref="pointcut2" returning="result"/>
public void writeLog(Object result){
System.out.println("writeLog "+result);
}
環繞通知:在目標方法執行前和後操做,能夠阻止目標方法執行
<aop:around method="around" pointcut-ref="pointcut3"/>
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("before");
Object result=joinPoint.proceed();
System.out.println("after");
return result;
}
異常拋出通知:程序出現異常時操做
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut4" throwing="ex"/>
public void afterThrowing(Throwable ex){
System.out.println("exception "+ex.getMessage());
}
最終通知:至關於finally塊,不管代碼是否有異常,都會執行
<aop:after method="finallyFunc" pointcut-ref="pointcut4"/>
public void finallyFunc(){
System.out.println("finally");
}
引介通知:不經常使用
Spring 切入點表達式 基於 execution 函數完成
語法:[訪問修飾符] 方法返回值 包名.類名.方法名(參數)
其中任意字段可使用*代替表示任意值
Spring 的 AOP 基於 AspectJ 註解開發 開發步驟 引入jar包
設置配置文件:
<beans xmlns="www.springframework.org/schema/bean…"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xmlns:context="www.springframework.org/schema/cont…"
xmlns:aop="www.springframework.org/schema/aop"
xmlns:tx="www.springframework.org/schema/tx"
xsi:schemaLocation="www.springframework.org/schema/bean…
www.springframework.org/schema/bean…
www.springframework.org/schema/cont…
www.springframework.org/schema/cont…
www.springframework.org/schema/aop
www.springframework.org/schema/aop/…
www.springframework.org/schema/tx
www.springframework.org/schema/tx/s…">
編寫配置目標類
public class OrderDao {
public void save(){
System.out.println("save order");
}
public void update(){
System.out.println("update order");
}
public void delete(){
System.out.println("delete order");
}
public void find(){
System.out.println("find order");
}
}
開啓aop註解自動代理
編寫切面類並配置
@Aspect
public class MyAspectAnno {
@Before(value="execution(* demo1.OrderDao.save(..))")
public void before(){
System.out.println("before");
}
}
註解通知類型 @Before: 前置通知
@AfterReturning: 後置通知
@AfterReturning(value="execution(* demo1.OrderDao.save(..))",returning="result")
public void after(Object result){
System.out.println("after "+result);
}
@Around:環繞通知
@Around(value="execution(* demo1.OrderDao.save(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("before");
Object obj=joinPoint.proceed();
System.out.println("after");
return obj;
}
@AfterThrowing: 拋出異常
@AfterThrowing(value="execution(* demo1.OrderDao.save(..))",throwing="e")
public void afterThrowing(Throwable e){
System.out.println("exception:"+e.getMessage();
}
@After: 最終通知
@After(value="execution(* demo1.OrderDao.save(..))")
public void after(){
System.out.println("finally");
}
@PointCut:切入點註解
@PointCut(value="execution(* demo1.OrderDao.save(..))")
private void pointcut1(){}
此時,在上述通知的註解中,value能夠替換爲該函數名,例如:
@After(value="MyAspect.pointcut1()")
public void after(){
System.out.println("finally");
}
這個註解的好處是,只須要維護切入點便可,不用在修改時修改每一個註解。
Spring 的 JDBC 模板 Spring 對持久層也提供瞭解決方案,也就是 ORM 模塊和 JDBC 的模板。針對 JDBC ,提供了 org.springframework.jdbc.core.JdbcTemplate 做爲模板類。
使用 JDBC 模板 引入jar包,數據庫驅動,Spring 的 jdbc 相關包。
基本使用:
public void demo1(){
//建立鏈接池
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring4");
dataSource.setUsername("root");
dataSource.setPassword("123456");
//建立JDBC模板
JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
jdbcTemplate.update("insert into account values (null,?,?)", "xiaoming",1000d);
}
將鏈接池和模板交給 Spring 管理
配置文件:
測試文件:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcDemo2 {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Test
public void demo2(){
jdbcTemplate.update("insert into account values (null,?,?)", "xiaolan",1000d);
}
}
使用開源數據庫鏈接池 使用 DBCP 的配置:
使用 C3P0 的配置:
引入外部屬性文件
首先創建外部屬性文件:
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.66.128/spring4
jdbc.username=root
jdbc.password=123456
而後對屬性文件進行配置:
<context:property-placeholder location="classpath:jdbc.properties"/>
CRUD操做 insert, update, delete 語句都藉助模板的 update 方法進行操做。
public void demo(){
jdbcTemplate.update("insert into account values (null,?,?)", "xiaoda",1000d);
jdbcTemplate.update("update account set name=?,money=? where id=?", "xiaoda",1000d,2);
jdbcTemplate.update("delete from account where id=?", 6);
}
查詢操做:
public void demo3(){
String name=jdbcTemplate.queryForObject("select name from account where id=?",String.class,5);
long count=jdbcTemplate.queryForObject("select count(*) from account",Long.class);
}
將返回的結果封裝成爲類:
public void demo4(){
Account account=jdbcTemplate.queryForObject("select * from account where id=?", new MyRowMapper(),5);
}
其中:
class MyRowMapper implements RowMapper{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account=new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getDouble("money"));
return account;
}
}
Spring的事務管理 事務 事務是指邏輯上的一組操做,組成這組操做的各個單元,要麼所有成功,要麼所有失敗。
具備四個特性:
原子性:事務不可分
一致性:事務執行先後數據完整性保持一致
隔離性:一個事務的執行不該該受到其餘事務干擾
持久性:一旦事務結束,數據就持久化到數據庫
若是不考慮隔離性會引起安全性問題:
讀問題:
髒讀:一個事務讀到另外一個事務未提交的數據
不可重複讀:一個事務讀到另外一個事務已經提交的 update 數據,致使一個事務中屢次查詢結果不一致
幻讀:一個事務讀到另外一個事務已經提交的 insert 數據,致使一個事務中屢次查詢結果不一致
寫問題:
丟失更新
解決讀問題:設置事務隔離級別
Read uncommitted: 未提交讀,沒法解決任何讀問題
Read committed: 已提交讀,解決髒讀問題
Repeatable read: 重複讀,解決髒讀和不可重複讀問題
Serializable:序列化,解決全部讀問題
事務管理API PlatformTransactionManager: 平臺事務管理器
這是一個接口,擁有多個不一樣的實現類,如 DataSourceTransactionManager 底層使用了JDBC 管理事務; HibernateTransactionManager 底層使用了 Hibernate 管理事務。
TransactionDefinition: 事務定義信息
用於定義事務的相關信息,如隔離級別、超時信息、傳播行爲、是否只讀等
TransactionStatus: 事務的狀態
用於記錄在事務管理過程當中,事務的狀態的對象。
上述API的關係: Spring 在進行事務管理的時候,首先平臺事務管理器根據事務定義信息進行事務管理,在事務管理過程中,產生各類此狀態,將這些狀態信息記錄到事務狀態的對象當中。
事務的傳播行爲 事務的傳播行爲主要解決業務層(Service)方法相互調用的問題,也就是不一樣的業務中存在不一樣的事務時,如何操做。
Spring 中提供了7種事務的傳播行爲,分爲三類:
保證多個操做在同一個事務中
PROPAGATION_REQUIRED: B方法調用A方法,若是A中有事務,使用A中的事務並將B中的操做包含到該事務中;不然新建一個事務,將A和B中的操做包含進來。(默認)
PROPAGATION_SUPPORTS:若是A中有事務,使用A的事務;不然不使用事務
PROPAGATION_MANDATORY:若是A中有事務,使用A的事務;不然拋出異常
保證多個操做不在同一個事務中
PROPAGATION_REQUIRES_NEW:若是A中有事務,將其掛起,建立新事務,只包含自身操做。不然,新建一個事務,只包含自身操做。
PROPAGATION_NOT_SUPPORTED:若是A中有事務,掛起,不使用事務。
PROPAGATION_NEVER:若是A中有事務,拋出異常,也即不能用事務運行。
嵌套事務
PROPAGATION_NESTED:若是A有事務,按照A的事務執行,執行完成後,設置一個保存點,而後執行B的操做。若是出現異常,能夠回滾到最初狀態或保存點狀態。
實例 以轉帳爲例,業務層的DAO層類以下:
public interface AccountDao {
public void outMoney(String from,Double money);
public void inMoney(String to,Double money);
}
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{
@Override
public void outMoney(String from, Double money) {
this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,from);
}
@Override
public void inMoney(String to, Double money) {
this.getJdbcTemplate().update("update account set money = money + ? where name = ?",money,to);
}
}
public interface AccountService {
public void transfer(String from,String to,Double money);
}
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String from, String to, Double money) {
accountDao.outMoney(from, money);
accountDao.inMoney(to, money);
}
}
在xml中進行類的配置:
事務管理1: 編程式事務管理 配置平臺事務管理器
配置事務管理模板類
在業務層注入事務管理模板
編碼實現事務管理
//ServiceImpl類中:
private TransactionTemplate transactionTemplate;
@Override
public void transfer(String from, String to, Double money) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus arg0) {
accountDao.outMoney(from, money);
accountDao.inMoney(to, money);
}
});
}
聲明式事務管理(配置實現,基於AOP思想) XML 方式的聲明式事務管理
配置事務管理器
配置事務通知
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:method name="transfer" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
配置aop事務
<aop:pointcut expression="execution(* tx.demo2.AccountServiceImpl.*(..))" id="pointcut1"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>
</aop:config>
註解方式
配置事務管理器,和上方一致
開啓事務管理的註解:
<tx:annotation-driven transaction-manager="transactionManager"/>
在使用事務的類上添加一個註解@Transactional