主頁 > 後端開發 > Spring

Spring

2021-09-20 06:56:46 後端開發

1.Spring

1.簡介

Spring : 春天 --->給軟體行業帶來了春天

2002年,Rod Jahnson首次推出了Spring框架雛形interface21框架,

2004年3月24日,Spring框架以interface21框架為基礎,經過重新設計,發布了1.0正式版,

很難想象Rod Johnson的學歷 , 他是悉尼大學的博士,然而他的專業不是計算機,而是音樂學,

Spring理念 : 使現有技術更加實用 . 本身就是一個大雜燴 , 整合現有的框架技術

官網 : http://spring.io/

官方下載地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

2.優點

1、Spring是一個開源免費的框架 , 容器 .

2、Spring是一個輕量級的框架 , 非侵入式的 .

3、控制反轉 IoC , 面向切面 Aop

4、對事物的支持 , 對框架的支持

.......

一句話概括:

Spring是一個輕量級的控制反轉(IoC)和面向切面(AOP)的容器(框架),

3.組成

Spring 框架是一個分層架構,由 7 個定義良好的模塊組成,Spring 模塊構建在核心容器之上,核心容器定義了創建、配置和管理 bean 的方式 .

組成 Spring 框架的每個模塊(或組件)都可以單獨存在,或者與其他一個或多個模塊聯合實作,每個模塊的功能如下:

  • 核心容器:核心容器提供 Spring 框架的基本功能,核心容器的主要組件是 BeanFactory,它是工廠模式的實作,BeanFactory 使用控制反轉(IOC) 模式將應用程式的配置和依賴性規范與實際的應用程式代碼分開,
  • Spring 背景關系:Spring 背景關系是一個組態檔,向 Spring 框架提供背景關系資訊,Spring 背景關系包括企業服務,例如 JNDI、EJB、電子郵件、國際化、校驗和調度功能,
  • Spring AOP:通過配置管理特性,Spring AOP 模塊直接將面向切面的編程功能 , 集成到了 Spring 框架中,所以,可以很容易地使 Spring 框架管理任何支持 AOP的物件,Spring AOP 模塊為基于 Spring 的應用程式中的物件提供了事務管理服務,通過使用 Spring AOP,不用依賴組件,就可以將宣告性事務管理集成到應用程式中,
  • Spring DAO:JDBC DAO 抽象層提供了有意義的例外層次結構,可用該結構來管理例外處理和不同資料庫供應商拋出的錯誤訊息,例外層次結構簡化了錯誤處理,并且極大地降低了需要撰寫的例外代碼數量(例如打開和關閉連接),Spring DAO 的面向 JDBC 的例外遵從通用的 DAO 例外層次結構,
  • Spring ORM:Spring 框架插入了若干個 ORM 框架,從而提供了 ORM 的物件關系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map,所有這些都遵從 Spring 的通用事務和 DAO 例外層次結構,
  • Spring Web 模塊:Web 背景關系模塊建立在應用程式背景關系模塊之上,為基于 Web 的應用程式提供了背景關系,所以,Spring 框架支持與 Jakarta Struts 的集成,Web 模塊還簡化了處理多部分請求以及將請求引數系結到域物件的作業,
  • Spring MVC 框架:MVC 框架是一個全功能的構建 Web 應用程式的 MVC 實作,通過策略介面,MVC 框架變成為高度可配置的,MVC 容納了大量視圖技術,其中包括 JSP、Velocity、Tiles、iText 和 POI,

4.拓展

Spring Boot與Spring Cloud

  • Spring Boot 是 Spring 的一套快速配置腳手架,可以基于Spring Boot 快速開發單個微服務;
  • Spring Cloud是基于Spring Boot實作的;
  • Spring Boot專注于快速、方便集成的單個微服務個體,Spring Cloud關注全域的服務治理框架;
  • Spring Boot使用了約束優于配置的理念,很多集成方案已經幫你選擇好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot來實作,Spring Boot可以離開Spring Cloud獨立使用開發專案,但是Spring Cloud離不開Spring Boot,屬于依賴的關系,
  • SpringBoot在SpringClound中起到了承上啟下的作用,如果你要學習SpringCloud必須要學習SpringBoot,

2.Spring—IOC

1.在Maven專案中添加Spring依賴

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.9</version>
    </dependency>
</dependencies>

2.IOC的本質

控制反轉IoC(Inversion of Control),是一種設計思想,DI(依賴注入)是實作IOC的一種方法,在沒有IoC的程式中,我們使用面向物件的編程,物件的創建與物件間的依賴關系完全硬編碼在程式中,物件的創建由程式自己控制,控制反轉將物件的創建轉移給第三方,個人認為所謂控制反轉就是:獲得依賴物件的方式反轉了,

采用XML方式配置Bean的時候,Bean的定義資訊是和實作分離的,而采用注解的方式可以把兩者合為一體,Bean的定義資訊直接以注解的形式定義在實作類中,從而達到了零配置的目的,

控制反轉是通過描述(XML或注解)并通過第三方去生產或獲取特定物件的方式,在Spring中實作控制反轉的是IoC容器,其實作方法是依賴注入(Dependency Injection,DI),

3.配置Spring的元資料

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="hello" >
       <property name="name" value="https://www.cnblogs.com/aadzj/p/dengzhijiang"></property>
   </bean>
    <!-- more bean definitions go here -->
</beans>

4.獲取Spring的背景關系物件

讀取容器

ApplicationContext context = new ClassPathXmlApplicationContext("benas.xml");

5.Spring創建物件

<bean id="userService" >
    <!--
        ref:參考Spring容器中已經創建好的物件
        value:基本的值,基本資料型別
    -->
    <property name="userDao" ref="oracle"></property>
</bean>

6.不同資料型別的注入方式

	private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
<bean id="address" >
        <property name="address" value="https://www.cnblogs.com/aadzj/p/湛江市"></property>
    </bean>
    <bean id="student" >
        <!--第一種,普通值注入,value-->

        <property name="name" value="https://www.cnblogs.com/aadzj/p/鄧志江" />
        <!--第二種,bean注入,ref-->
        <property name="address" ref="address"/>

        <!--陣列-->
        <property name="books">
            <array>
                <value>紅樓夢</value>
                <value>西游記</value>
                <value>水滸傳</value>
                <value>三國演義</value>
            </array>
        </property>
        <!--List-->
        <property name="hobbies">
            <list>
                <value>聽歌</value>
                <value>寫字</value>
                <value>運動</value>
            </list>
        </property>
        <!--map-->
        <property name="card">
            <map>
                <entry key="省份證" value="https://www.cnblogs.com/aadzj/p/44088219981211"></entry>
                <entry key="銀行卡" value="https://www.cnblogs.com/aadzj/p/201824113212"></entry>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--null-->
        <property name="wife">
            <null/>
        </property>
        <!--properties-->
        <property name="info">
            <props>
                <prop key="driver">20182411</prop>
                <prop key="gender">男</prop>
                <prop key="username">小明</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>

7.擴展方式注入

c命名空間和p命名空間的注入:不能直接使用,需要匯入xml約束

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<!--p命名空間注入,可以直接注入屬性的值,property-->
<bean id="user"  p:name="鄧志江" p:age="22"></bean>
<!--c命名空間注入,通過構造器注入,construct-args-->
<bean id="user2"  c:name="林勇" c:age="22" ></bean>

8.bean的作用域

1、單例模式(Spring默認模式)

<bean id="user"  p:name="鄧志江" p:age="22" scope="singleton"></bean>

2、原型模式(每次從容器中get的時候,都會產生一個新的物件!

<bean id="user2"  c:name="林勇" c:age="22" scope="prototype"></bean>

3、其余的 @request、@sesstion、@application 這些只能在web開發中使用到!

9.bean的自動裝配

  1. autowired:byName ---> 必須保證所有的 bean 的 id 的唯一,并且這個 bean 需要和自動注入的屬性的 set 方法的值一致,
  2. autowired:byType ---> 必須保證所有的 bean 的 class 的唯一,并且這個 bean 需要和自動注入的屬性的型別一致!
private String name;
@Autowired
private Cat cat;
@Autowired
private Dog dog;
<!--自動裝配需要加上-->
<context:annotation-config/>
<bean id="cat" ></bean>
<bean id="dog" ></bean>
<!--
    byName: 會自動在容器的背景關系中查找,和自己物件set方法后面值對應的 beanid!
    byType: 會自動在容器的背景關系中查找,和自己物件屬性型別相同的 bean!
-->
<bean id="person"  autowire="byName">
    <property name="name" value="https://www.cnblogs.com/aadzj/p/小公羊"/>
    <!--<property name="cat" ref="cat"/>-->
    <!--<property name="dog" ref="dog"/>-->
</bean>

注解說明

-@autowired:自動裝配通過型別、名字

? 如果@autowired沒有自動裝配上屬性,則需要通過@qualifier(value = https://www.cnblogs.com/aadzj/p/“ ”)

-@nullable 如果欄位標記了這個注解,說明這個欄位可以為null

-@resource:自動裝配通過型別、名字

將類注冊到容器中

-@component :組件,放在這個類上,說明這個類被Spring管理了,就是bean!

? 等價于:

-@Value: 給屬性賦值,等價于:

<!--需要在 xml 中開啟注解掃描,才能檢測到注冊bean的類-->
<context:component-scan base-package="com.dzj.dao"/>

@component組件的衍生:在web開發中,會按照三層架構分層

dao【@Repository】

service【@Service】

controller【@Controller】

這四個注解功能都是一樣的,都是將我們的類注冊到Spring容器

10.在純java類中配置的方法

第一種方法:

1、在物體類的頭部添加注解--@component

@Value注解用來給物件的屬性賦值

@Component
public class User {
    @Value("zhijiang")
    public String name;

    public void show(){
        System.out.println("成功了...");
    }
}

2、在配置類 MyConfig 中添加兩個注解

--@configuration ---> 代替 beans.xml 檔案,相當于這個類就是一個spring容器

--@componentScan --> 用來掃描物體類,哪些類注冊了 bean

@Configuration
@ComponentScan("com.dzj.pojo")
public class MyConfig {

}

3、獲取容器中的物件

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("user", User.class);

第二種方法:

1、無需在物體類中添加多余的注解,若想給物件的屬性賦值,只需用@Value注解給屬性賦值即可

public class User {
    @Value("zhijiang")
    public String name;
    public void show(){
        System.out.println("成功了...");
    }
}

2、只需在配置類中添加一個回傳物件的方法,并且在該方法上方添加一個注解@bean

public class MyConfig {
    @Bean
    public User getUser(){
        return new User();
    }
}

@bean就是beans.xml檔案中的

方法名:getUser就是標簽中的 id

new user():就是就是標簽中的class

3、獲取容器中的物件

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser", User.class);

3.Spring—AOP

1.聊聊AOP

2.動態代理

2.1.被代理的介面
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}
2.2.介面的實作類(真實角色)
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("添加了一個用戶");
    }

    public void delete() {
        System.out.println("洗掉了一個用戶");
    }

    public void update() {
        System.out.println("修改了一個用戶");
    }

    public void query() {
        System.out.println("查詢了一個用戶");
    }
}
2.3.自動生成代理類的中間類
//等會我們用這個類,自動生成代理類
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的介面
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    //生成得到代理類
    public Object getProxy(){
        return  Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }

    //處理代理實體,并回傳結果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        PrintLog(method.getName());
        Object result = method.invoke(target,args);
        fee();
        return result;
    }

    public void PrintLog(String msg){
        System.out.println("[debug]執行了"+msg+"方法!");
    }
    public void fee(){
        System.out.println("收中介費");
    }

}
2.4.執行類
public static void main(String[] args) {

    //真實角色
    UserServiceImpl userService = new UserServiceImpl();

    //代理角色,不存在,從ProxyInvocationHandler類中動態生成
    ProxyInvocationHandler pih = new ProxyInvocationHandler();
    //在 ProxyInvocationHandler 類中通過setTarget()方法得到要被代理的真是角色 userService
    pih.setTarget(userService);
    // 獲取代理角色
    UserService proxy = (UserService) pih.getProxy();
    proxy.add();  //執行代理實體,以及一些附屬的操作
}

3.在Spring中實作AOP

1.使用原生態 API介面

使用原生態 API介面**(主要是SpringAPI介面實作)

1. 創建介面,包含真實角色要實作的抽象方法
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}
2. 實作介面的類(真實角色)
public class UserServiceImpl implements UserService {

    public void add() {
        System.out.println("添加了一個用戶!");
    }

    public void delete() {
        System.out.println("洗掉了一個用戶!");
    }

    public void update() {
        System.out.println("修改了一個用戶!");
    }

    public void query() {
        System.out.println("查詢了一個用戶!");
    }
}
3. 執行環繞增強的類
public class Log implements MethodBeforeAdvice {

    //method:要執行的目標物件的方法
    //args:引數
    //target:目標物件
    public void before(Method method, Object[] args, Object target) throws Throwable {

        System.out.println(target.getClass().getName()+"的"+method.getName()+"被執行了");

    }
}
public class AfterLog implements AfterReturningAdvice {

    //returnValue:回傳值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {

        System.out.println("執行了"+method.getName()+"方法,回傳結果為:"+returnValue);
    }
}
4. 創建并配置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:aop="http://www.springframework.org/schema/aop"       												xsi:schemaLocation="http://www.springframework.org/schema/beans        			   							https://www.springframework.org/schema/beans/spring-beans.xsd        		  								http://www.springframework.org/schema/aop        
   	https://www.springframework.org/schema/aop/spring-aop.xsd">    
    <!--注冊bean-->    
    <bean id="userService" />    
    <bean id="log" />    
    <bean id="afterLog" />    
    <!--方式一:使用原生態 API介面-->    
    <!--配置aop:需要匯入aop的約束-->    
    <aop:config>        
        <!--創建切入點:expression:運算式,excution(要執行的位置!* * * * *)-->        
        <aop:pointcut id="pointcut" expression="execution(* com.dzj.service.UserServiceImpl.*(..))" />        		  <!--執行環繞增強,把增強引入切入點-->        
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>        
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>    
    </aop:config>
</beans>
5. 添加測驗類
public class MyTest {    
    public static void main(String[] args) {        
    	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");       
    	//動態代理的是介面,而不是介面的實作類        
    	UserService userService = context.getBean("userService", UserService.class);
        userService.query();    
    }
}

2.自定義類(主要是切面定義)

1. 創建被代理的介面
public interface UserService {    
    public void add();    
    public void delete();    
    public void update();    
    public void query();
}
2. 實作被代理介面的類(真實角色)
public class UserServiceImpl implements UserService {    
    public void add() {        
        System.out.println("添加了一個用戶!");    
    }    
    public void delete() {        
        System.out.println("洗掉了一個用戶!");    
    }    
    public void update() {        
        System.out.println("修改了一個用戶!");    
    }    
    public void query() {        
        System.out.println("查詢了一個用戶!");    
    }
}
3. 自定義類
public class diy {    
    public void before(){        
        System.out.println("*****方法執行前*****");    
    }    
    public void after(){        
        System.out.println("*****方法執行后*****");    
    }
}
4. applicationContext.xml 組態檔
<!--注冊bean-->
<bean id="userService" />
<bean id="log" />
<bean id="afterLog" />
<!--方式二:自定義類-->
<bean id="diy" />
<aop:config>    
    <!--自定義切面,ref 要參考的類-->    
    <aop:aspect ref="diy">        
        <!--切入點-->        
        <aop:pointcut id="point" expression="execution(* com.dzj.service.UserServiceImpl.*(..))"/>
        <!--通知-->        
        <aop:before method="before" pointcut-ref="point"/>        
        <aop:after method="after" pointcut-ref="point"/>    
    </aop:aspect>
</aop:config>
5. 測驗類
public class MyTest {    
    public static void main(String[] args) {        
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //動態代理的是介面,而不是介面的實作類       
        UserService userService = context.getBean("userService", UserService.class);
        userService.query();    
    }
}

3.使用注解

1. 創建一個類,通過 @Aspect 注解的方式標注為此類為一個切面
@Aspect  //標注這個類是一個切面
public class AnnotationPointCut {    
    @Before("execution(* com.dzj.service.UserServiceImpl.*(..))")    
    public void before(){        
        System.out.println("*****方法執行前*****");    
    }    
    @After("execution(* com.dzj.service.UserServiceImpl.*(..))")    
    public void after(){        
        System.out.println("*****方法執行后*****");    
    }    
    //在環繞增強中,我們可以給定一個引數,代表我們要獲取處理切入的點    
    @Around("execution(* com.dzj.service.UserServiceImpl.*(..))")    
    public void around(ProceedingJoinPoint jp) throws Throwable {        
        System.out.println("環繞前");        
        Signature signature = jp.getSignature();//獲得簽名        
        System.out.println("signature:"+signature);        
        Object proceed = jp.proceed();//執行方法        
        System.out.println("環繞后");     
    }
}
2. applicationContext.xml組態檔
<!--方式三-->
<!--創建切入點-->
<bean id="annotationPointCut" />
<!--開啟注解支持--><aop:aspectj-autoproxy/>
3. 被代理的介面、實作類、測驗類均不變

4、AOP在Spring中的作用

提供宣告式事務,允許用戶自定義切面

(1)橫切切入點:跨越應用程式多個模塊的功能和方法,即是,與我們邏輯無關的,但是我們需要關注的部分,就是橫切關注點,如日志、安全、快取、事務等等......

(2)切面(ASPECT):橫切關注點 被模塊化的特殊物件,即,它是一個類,

(3)通知(Advice):切面必須要完成的作業,即,它是類中的一個方法,

(4)目標(Tatget):被通知的物件,

(5)代理(Proxy):向目標物件應用通知之后創建的物件,

(6)切入點(PointCut):切面通知 執行的 “地點” 的定義,

(7)連接點(JoinPoint):與切入點匹配的執行點,

4.Spring-Mybatis

1. 回憶Mybatis

1. 新建一個物體類
@Data
public class User {
    private int uid;
    private String username;
    private String password;
}
2. 撰寫Mybatis核心組態檔
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <typeAliases>
        <package name="com.dzj.pojo"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="https://www.cnblogs.com/aadzj/p/com.mysql.jdbc.Driver"/>
                <property name="url" value="https://www.cnblogs.com/aadzj/p/jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="https://www.cnblogs.com/aadzj/p/root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <!-- 將mapper檔案加入到組態檔中,注冊介面 -->
    <mappers>
        <mapper ></mapper>
    </mappers>
</configuration>
3. 撰寫介面
public interface UserMapper {

    public List<User> selectUser();

}
4. 撰寫介面對應的xml檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.dzj.mapper.UserMapper">
    <select id="selectUser" resultType="user">
        select * from test.user;
    </select>
</mapper>
5. 撰寫測驗類
public class MyTest {

    @Test
    public void test() throws IOException {
        String resources = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resources);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sessionFactory.openSession(true);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userlist = mapper.selectUser();
        for(User user:userlist){
            System.out.println(user);
        }
    }
}

2. Mybatis-Spring

1. 撰寫資料源配置
<!--DataSource使用Spring的資料源替換Mybatis的配置  c3p0、dbcp、druid也可以
    我們這里使用Spring提供的JDBC : org.springframework.jdbc.datasource
-->
<bean id="dataSource" >
    <property name="driverClassName" value="https://www.cnblogs.com/aadzj/p/com.mysql.jdbc.Driver"/>
    <property name="url" value="https://www.cnblogs.com/aadzj/p/jdbc:mysql://localhost:3306/test"/>
    <property name="username" value="https://www.cnblogs.com/aadzj/p/root"/>
    <property name="password" value=""/>
</bean>
2. sqlSessionFactory
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" >
    <property name="dataSource" ref="dataSource"/>
    <!--系結Mybati組態檔-->
    <property name="configLocation" value="https://www.cnblogs.com/aadzj/p/classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="https://www.cnblogs.com/aadzj/p/classpath:com/dzj/mapper/*.xml"/>
</bean>
3. sqlSessionTemplate
<!--SqlSessionTemplate:就是我們使用的sqlSession-->
<bean id="sqlSession" >
    <!--只能使用構造器注入SQLSessionFactory,因為它沒有set方法-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
4. 需要給介面加實作類
public class UserMapperImpl implements UserMapper {    
    //我們所有的操作,都是用sqlSession來執行,在原來,現在都使用SqlSessionTemplate    
    private SqlSessionTemplate sqlSession;    
    public void setSqlSession(SqlSessionTemplate sqlSession) {        
        this.sqlSession = sqlSession;    
    }    
    public List<User> selectUser() {       
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);       
        return mapper.selectUser(); 
    }
}
5. 將自己寫的實作類,注入到Spring中
<import resource="spring-dao.xml"/>
<bean id="userMapper" >    
    <property name="sqlSession" ref="sqlSession"/>
</bean>
6. 測驗
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for(User user:userMapper.selectUser()){    
    System.out.println(user);
}

5.宣告式事務

1. 事務的特點

  • 把一組業務當成一個業務來做,要么都成功要么都失敗,
  • 事務在專案開發中,十分的重要,涉及到資料的一致性問題,不能馬虎,
  • 確保一致性和完整性

事務ACID原則:

  • 原子性
  • 一致性
  • 隔離性
    • 多個業務可能同時操作同一個資源,防止資料損壞,
  • 持久性
    • 事務一旦被提交,無論系統發生什么問題,結果都不會被影響,被持久化的寫到存盤器中,

2. 事務的配置

	<!--配置宣告式事務-->
    <bean id="transactionManager" >
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--結合AOP實作事務的織入-->
    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--給哪些事務配置方法-->
        <!--配置事務的傳播特性:new propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
            <!--"name*" 代表所有方法-->
        </tx:attributes>
    </tx:advice>

    <!--配置事務的切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.dzj.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>	

3. spring中的事務管理

Spring在不同的事務管理API之上定義了一個抽象層,使得開發人員不必了解底層的事務管理API就可以使用Spring的事務管理機制,Spring支持編程式事務管理和宣告式的事務管理,

編程式事務管理

  • 將事務管理代碼嵌到業務方法中來控制事務的提交和回滾
  • 缺點:必須在每個事務操作業務邏輯中包含額外的事務管理代碼

宣告式事務管理

  • 一般情況下比編程式事務好用,
  • 將事務管理代碼從業務方法中分離出來,以宣告的方式來實作事務管理,
  • 將事務管理作為橫切關注點,通過aop方法模塊化,Spring中通過Spring AOP框架支持宣告式事務管理,

使用Spring管理事務,注意頭檔案的約束匯入 : tx

xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

事務管理器

  • 無論使用Spring的哪種事務管理策略(編程式或者宣告式)事務管理器都是必須的,
  • 就是 Spring的核心事務管理抽象,管理封裝了一組獨立于技術的方法,

JDBC事務

<bean id="transactionManager" >
       <property name="dataSource" ref="dataSource" />
</bean>

配置好事務管理器后我們需要去配置事務的通知

<!--配置事務通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
       <!--配置哪些方法使用什么樣的事務,配置事務的傳播特性-->
       <tx:method name="add" propagation="REQUIRED"/>
       <tx:method name="delete" propagation="REQUIRED"/>
       <tx:method name="update" propagation="REQUIRED"/>
       <tx:method name="search*" propagation="REQUIRED"/>
       <tx:method name="get" read-only="true"/>
       <tx:method name="*" propagation="REQUIRED"/>
   </tx:attributes>
</tx:advice>

spring事務傳播特性:

事務傳播行為就是多個事務方法相互呼叫時,事務如何在這些方法間傳播,spring支持7種事務傳播行為:

  • propagation_requierd:如果當前沒有事務,就新建一個事務,如果已存在一個事務中,加入到這個事務中,這是最常見的選擇,
  • propagation_supports:支持當前事務,如果沒有當前事務,就以非事務方法執行,
  • propagation_mandatory:使用當前事務,如果沒有當前事務,就拋出例外,
  • propagation_required_new:新建事務,如果當前存在事務,把當前事務掛起,
  • propagation_not_supported:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起,
  • propagation_never:以非事務方式執行操作,如果當前事務存在則拋出例外,
  • propagation_nested:如果當前存在事務,則在嵌套事務內執行,如果當前沒有事務,則執行與propagation_required類似的操作

Spring 默認的事務傳播行為是 PROPAGATION_REQUIRED,它適合于絕大多數的情況,

假設 ServiveX#methodX() 都作業在事務環境下(即都被 Spring 事務增強了),假設程式中存在如下的呼叫鏈:Service1#method1()->Service2#method2()->Service3#method3(),那么這 3 個服務類的 3 個方法通過 Spring 的事務傳播機制都作業在同一個事務中,

就好比,我們剛才的幾個方法存在呼叫,所以會被放在一組事務當中!

配置AOP

匯入aop的頭檔案!

<!--配置aop織入事務-->
<aop:config>
   <aop:pointcut id="txPointcut" expression="execution(* com.kuang.dao.*.*(..))"/>
   <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>

進行測驗

刪掉剛才插入的資料,再次測驗!

@Test
public void test2(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   UserMapper mapper = (UserMapper) context.getBean("userDao");
   List<User> user = mapper.selectUser();
   System.out.println(user);
}

思考問題?

為什么需要配置事務?

  • 如果不配置,就需要我們手動提交控制事務;
  • 事務在專案開發程序非常重要,涉及到資料的一致性的問題,不容馬虎!

本文來自博客園,作者:小公羊,轉載請注明原文鏈接:https://www.cnblogs.com/aadzj/p/15312220.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/301406.html

標籤:Java

上一篇:c++ STL之map詳解-小白入門

下一篇:全網最詳細的JavaWeb用戶管理系統(詳細原始碼講解)(小白也行)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more