1. 程式人生 > 其它 >Spring IOC 和 AOP

Spring IOC 和 AOP

Spring

建立的類在spring 中的生命週期, 控制權限交給了spring處理,拋棄了之前手動建立物件和例項物件。

 bean容器: 一個物件被建立和被例項化的過程發生的事。
 
 myclass --> 推斷構造器 --> 初始化前 --> 初始化中 --> 初始化後 --> 代理物件aop --> (IOC bean)單例池 --> Bean物件




spring的特性:

控制反轉 inversion of control : 指將物件的建立權力交給spring控制,每個物件稱為bean

依賴注入 dependency injection

: 依賴的物件不需要手動呼叫setxxx方法去設定,而是通過配置賦值

面向切面程式設計 aspect oriented programming : 在spring初始化例項物件前,通過切面設定,可以執行指定的切面方法。

spring容器: spring它是一個容器,我們的物件的生命週期在spring容器中控制著。

元件化:使用簡單的元件配置組合成一個複雜的應用。在 Spring 中可以使用XML和Java註解組合這些物件。

其他概念:

​ 單例: 一個類只有一個例項物件,例項化物件後將提供整系統使用。 bean是單例池,在多執行緒中,每個bean物件都只能存在一個單線中!

​ 同步機制:

​ ThreadLocal和執行緒同步機制相比有什麼優勢呢?他們都是為了解決多執行緒中相同變數的訪問衝突問題。在同步機制中,通過物件的鎖機制保證同一時間只有一個執行緒訪問變數。這時該變數是多個執行緒共享的,使用同步機制要求程式慎密地分析什麼時候對變數進行讀寫,什麼時候需要鎖定某個物件,什麼時候釋放物件鎖等繁雜的問題,程式設計和編寫難度相對較大。

概括起來說,對於多執行緒資源共享的問題,同步機制採用了“以時間換空間”的方式,而ThreadLocal採用了“以空間換時間”的方式。前者僅提供一份變數,讓不同的執行緒排隊訪問,而後者為每一個執行緒都提供了一份變數,因此可以同時訪問而互不影響。

spring核心:

1 控制反轉 inversion of control

為什麼要使用控制反轉:

bean物件變得靈活,應用物件的建立的權力交給spring管理,使用者可以通過spring容器獲取應用物件。

減少耦合度

實現的方式有哪些?

依賴注入DI:

​ 建構函式的依賴注入

​ 設值函式的依賴注入

​ 注入內部beans

​ 注入集合

推斷構造方法(預設的無參構造法)

Setter方法注入

使用xml配置應用物件

1.1 Bean

定義: bean是一個被例項化組裝,通過springioc管理的物件,並由容器提供的配置 元資料 建立的。

bean的屬性引數:
屬性 描述
class 這個屬性是強制性的,並且指定用來建立 bean 的 bean 類
name 起別名(name= a b c ..)可多個 這個屬性指定唯一的 bean 識別符號。在基於 XML 的配置元資料中,你可以使用 ID 和/或 name 屬性來指定 bean 識別符號。
scope 這個屬性指定由特定的 bean 定義建立的物件的作用域,它將會在 bean 作用域的章節中進行討論。
constructor-arg 它是用來注入依賴關係的,並會在接下來的章節中進行討論。
properties 它是用來注入依賴關係的,並會在接下來的章節中進行討論。
autowiring mode 它是用來注入依賴關係的,並會在接下來的章節中進行討論。
lazy-initialization mode 延遲初始化的 bean 告訴 IoC 容器在它第一次被請求時,而不是在啟動時去建立一個 bean 例項。
initialization 方法 在 bean 的所有必需的屬性被容器設定之後,呼叫回撥方法。它將會在 bean 的生命週期章節中進行討論。
destruction 方法 當包含該 bean 的容器被銷燬時,使用回撥方法。它將會在 bean 的生命週期章節中進行討論。
ref 引入內部bean物件
配置bean元資料的方式:
  • 基於 XML 的配置檔案
  • 基於註解的配置
  • 基於 Java 的配置
bean的後置處理器

初始化bean的前後對bean進行其他處理

如何做後置處理:

​ 繼承BeanPostProcessor 介面 實現初始化 前和初始化後方法。

public class InitHelloWorld implements BeanPostProcessor {
   public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("BeforeInitialization : " + beanName);
      return bean;  // you can return any other object as well
   }
   public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("AfterInitialization : " + beanName);
      return bean;  // you can return any other object as well
   }
}
bean的作用域

通過配置xml 中的 scope 指定哪種作用域

作用域 描述
singleton 在spring IoC容器僅存在一個Bean例項,Bean以單例方式存在,預設值
prototype 每次從容器中呼叫Bean時,都返回一個新的例項,即每次呼叫getBean()時,相當於執行newXxxBean()
request 每次HTTP請求都會建立一個新的Bean,該作用域僅適用於WebApplicationContext環境
session 同一個HTTP Session共享一個Bean,不同Session使用不同的Bean,僅適用於WebApplicationContext環境
global-session 一般用於Portlet應用環境,該作用域僅適用於WebApplicationContext環境
基於xml配置bean物件
<?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-3.0.xsd">

   <bean id="" class="" 
      scope="">
   </bean>

</beans>
import

當有多個bean.xml配置檔案時,可以通過總的application.xml檔案用Import到管理多個bean.xml檔案

application.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <import resource="bean.xml"/>
    <import resource="bean1.xml"/>


</beans>```

2 依賴注入

​ 給bean物件賦值元資料,元資料可以是引用class (注入內部Bean),有參構造方法,普通元數, 集合等複雜的資料賦值。

基本注入

2.1 有參構造方法

2.2 內部Bean注入

2.3 普通引數注入

2.4 集合引數注入

​ set , map ,array , 屬性propr, null

類元資料
	private String beanname;
    private BeanLife beanLife; //內部Bena注入
    //集合注入
    private Set<String> setdi;
    private Map<String,String> mapdi;
    private String[] arrayListdi;
    private String nulldi;
    private Properties propertiesdi;

<?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-3.0.xsd">
    內部bean
    <bean id="beanLife" class="spring.bean.BeanLife"/>

    <bean id="beanDI" class="spring.bean.BeanDI">
        <!--基本引數-->
       <property name="beanname" value="hellobean"/>

        <!-- 內部bean-->
        <property name="beanLife" ref="beanLife"/>

        <!-- 集合-->
        set
        <property name="setdi">
            <set>
                <value>set值</value>
                <value>set值1</value>
            </set>
        </property>
        map
        <property name="mapdi">
           <map>
               <entry key="用名" value="root"></entry>
               <entry key="密碼" value="root"></entry>
           </map>
        </property>
        陣列
        <property name="arrayListdi">
            <array>
                <value>西縣及</value>
                <value>陣列型別</value>
            </array>
        </property>
        null
        <property name="nulldi">
            <null/>
        </property>
        
        屬性propety
        <property name="propertiesdi">
            <props>
                <prop key="one">INDIA</prop>
                <prop key="two">Pakistan</prop>
                <prop key="three">USA</prop>
                <prop key="four">USA</prop>
            </props>
        </property>



    </bean>

</beans>

簡化注入

2.5 p 標籤注入

xmlns:p="http://www.springframework.org/schema/p" 引入

屬性名稱空間注入
傳統的屬性引數 property name = "pname" value ="valuename"  ===  p:pname="valuename"

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
	傳統屬性注入
    <bean name="classic" class="com.example.ExampleBean">
        <property name="email" value="[email protected]"/>
    </bean>
	
    p命名注入
    <bean name="p-namespace" class="com.example.ExampleBean"
        p:email="[email protected]"/>
    
    注入的是內部bean物件時   p:spouse-ref
	    <bean name="classic" class="com.example.ExampleBean" 
              p:name = "Jane Doe" p:spouse-ref = "user"
              >
         <bean name="user" class="com.example.User">
            <property name="name" value="Jane Doe"/>
        </bean>     

</beans>


2.6 c 標籤注入

配置有參建構函式引數注入

xmlns:c="http://www.springframework.org/schema/c"
<!--    使用c p 標籤簡化注入-->
 <bean id="userBean" class="spring.bean.UserBean" p:beanname="helloUserBean" c:beanname="有參構造"/>

2.7 depends-on

用來指定多個內部bean物件

depends-on 屬性既可以指定初始化時間依賴,也可以指定對應的銷燬時間依賴(僅在單例 bean 的情況下)。 與給定 bean 定義依賴關係的依賴 bean 首先被銷燬,在給定 bean 本身被銷燬之前。 因此,depends-on 也可以控制關閉順序。

<bean id="beanOne" class="ExampleBean" depends-on="bean1,bean2">
    <property name="manager" ref="manager" />
</bean>

<bean id="bean1" class="ManagerBean" />
<bean id="bean2" class="x.y.jdbc.JdbcAccountDao" />


3.自動裝配 autowired

沒有自動裝配之前,我們用xml配置內部Bean物件屬性,通過 ref 或者p標籤 p:spouse-ref,引入內部Bena的元資料。

現在用自動裝配 autowired="byName/byType" ,自己去容器找到內部類的屬性名和型別。

byName:內部bean物件屬性名
byType: 內部bean物件資料型別
	<!--    自動裝配-->
	兩個內部類
    <bean id="man" class="spring.bean.userclass.Man"/>
    <bean id="gegir" class="spring.bean.userclass.Gegir"/>

	bean物件
    <bean id="proson"  class="spring.bean.userclass.Proson" p:name="人們" autowire="byType">

    </bean>

建構函式的自動裝配 constructor-arg
<!--    自動裝配-->
    <bean id="man" class="spring.bean.userclass.Man"/>
    <bean id="gegir" class="spring.bean.userclass.Gegir"/>

    <bean id="proson"  class="spring.bean.userclass.Proson" p:name="人們" autowire="constructor">
        <constructor-arg value="這是man建構函式"/>
        <constructor-arg value="這是gegir建構函式"/>
    </bean>

4.面向切面AOP

面向切面是基於動態代理的反射機制,通過建立代理物件,可以將方法切入到指定目標類方法前後,或者環繞,或者拋異常

建立aop的方法有哪些

  1. 原生的spring api

  2. 基於 bean.xml 配置檔案

  3. 基於註解

什麼是切面(<aop:aspect ref="日誌類"> 自定義的切入面)

​ 切入目標類的,代理類

什麼是切點(expression="execution(* aop.serve.UserServceImp.*(..)))又是實現類

​ 切入點是被代理類的方法執行的目標類

每個類執行完方法之前和之後切入面類的方法就會根據應用場景來執行你方法的前後通知

依賴Spring5的AOP依賴

   <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

基於xml配置實現AOP

場景:

​ 我有一個數據庫操作的業務類,它繼承了userDao並實現增刪改查方法,userDaoImp繼承類執行sql的業務操作。 我想在執行sql操作的前後都加一個通過,執行中,和執行完成

UserDao.interface

package aop.dao;

public interface UserDao {
    public void add();
    public void delete();
    public void update();
    public void select();
    public void insert();
}

UserServceImp.class

package aop.serve;


import aop.dao.UserDao;

public class UserServceImp implements UserDao {
    @Override
    public void add() {
        System.out.println("執行新增操作");
    }

    @Override
    public void delete() {
        System.out.println("刪除");
    }

    @Override
    public void update() {
        System.out.println("更新");
    }

    @Override
    public void select() {
        System.out.println("查詢");
    }

    @Override
    public void insert() {
        System.out.println("插入");
    }

}

切面類Logger.class

public class Logger {

    public void befor(){
        System.out.println("正在執行操作!");
    }
    public void after(){
        System.out.println("執行完成!");
    }
    
 }

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

    注入bean物件
    <bean id="userServceImp" class="aop.serve.UserServceImp"/>
    <bean id="logger" class="aop.log.Logger"/>
    
    
    配置aop
    <aop:config>

        <!--自定義的日誌切面-->
        <aop:aspect ref="logger">
            <aop:pointcut id="pointcut" expression="execution(* aop.serve.UserServceImp.*(..))"/>
            <aop:before method="befor" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>

    </aop:config>
    
    
    
</beans>
execution( * * * * ) 五個 * 號所代表的含義

execution( 返回值型別 切點類路徑 子包 所有類 所有方法)

符號 含義
execution() 表示式的主體;
1 第一個”*“符號 表示返回值的型別任意;
2 com.sample.service.impl AOP所切的服務的包名,即,我們的業務部分
3 包名後面的”..“ 表示當前包及子包
4 第二個”*“ 表示類名,*即所有類。此處可以自定義,下文有舉例
5 .*(..) 表示任何方法名,括號表示引數,兩個點表示任何引數型別

Spring註解

一 IOC註解

簡化之前的bean.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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    開啟註解模式
   <context:annotation-config/>

 

</beans>

Bean (@component )

@Component

等價於 xml 中的標籤 ,指定名稱用 @component("user") ===

開啟元件掃描
<context:component-scan  base-package=“掃描包下帶有component的類”/>
生命週期

作用域@Scope
@Scope(“singleton”):單例模式
@Scope(“prototype”):多例模式

依賴注入

普通引數的依賴注入@Value
注入集合
建構函式的注入
內部Bean物件的注入

自動裝配 @Autowired @Resource

解決內部bean物件的byName屬性名和byType型別,構造方法等元資料

@Resource
private Man man;
@Autowired
private Gegir gegir;
<!--    開啟註解模式-->
    <context:annotation-config/>
	autowired註解
    <bean id="gegir1" class="spring.bean.userclass.Gegir"/>

	resouce註解 javax自帶的
    <bean id="man" class="spring.bean.userclass.Man"/>
    <bean id="man2" class="spring.bean.userclass.Man"/>

    <bean id="proson" class="spring.bean.userclass.Proson"/>

@Autowired @Resourc的區別
  1. 功能相同都是用來自動裝配的,都可以放在內部bean物件上
  2. @Autowired通過byname方法來實現
  3. @Resourc通過byname方法來實現,如果找不到屬性名,則通過byType實現

其他註解

JSR250

bean的初始化 @PostConstruct 註釋作為初始化回撥函式的一個替代,

bean的銷燬 @PreDestroy 註釋作為銷燬回撥函式的一個替代

@Required 註解應用於 bean 屬性的 setter 方法**

@Qualifier 指定bean.xml中使用的是哪某個beans物件
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Profile {
   @Autowired
   @Qualifier("student1")  指定bean.xml另外的byName值
   private Student student;
   public Profile(){
      System.out.println("Inside Profile constructor." );
   }
   public void printAge() {
      System.out.println("Age : " + student.getAge() );
   }
   public void printName() {
      System.out.println("Name : " + student.getName() );
   }
}
<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>

   <!-- Definition for profile bean -->
   <bean id="profile" class="com.tutorialspoint.Profile">
   </bean>

   <!-- 同個byTpye 不同byName -->
   <bean id="student1" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>
   </bean>

   <bean id="student2" class="com.tutorialspoint.Student">
      <property name="name"  value="Nuha" />
      <property name="age"  value="2"/>
   </bean>

</beans>

二 AOP註解

切點@Pointcut("execution(* 目標類路徑 *(..))")

切面@Aspect

前置通知 @Before

後置通知 @After

環繞通知 @Around

最後環繞通知 @AfterReturning(pointcut = "", returning="返回值")

異常通知 @AfterThrowing(pointcut = "", throwing = "拋異常的引數")

實現

注入bean

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

    <!--開啟切面註解-->
    <aop:aspectj-autoproxy/>

    切面
    <bean id="aLogger" class="aop.annotation.ALogger"/>
    切點
    <bean id="aUserDaoImp" class="aop.annotation.AUserDaoImp"/>



</beans>

日誌註解切面

package aop.annotation;


import org.aspectj.lang.annotation.*;

@Aspect
public class ALogger {
	
    單獨抽取指向切點的方法供其他切面方法使用
    @Pointcut("execution(* aop.annotation.AUserDaoImp.*(..))")
    public void selecall(){}

    @Before("selecall()")
    public void befor(){
        System.out.println("執行之前!");
    }

    @After("selecall()")
    public void after(){
        System.out.println("執行之後!");
    }

    public void aroutd(){ System.out.println("在方法之前之後,環繞通知");}
    public void afterreturning(){
        System.out.println("afterreturning");
    }

    @AfterThrowing(pointcut = "selecall()", throwing = "E")
    public void throwing(IllegalArgumentException  E){
        System.out.println("throwing"+ E.toString());
    }


}

切點

import org.springframework.stereotype.Component;

@Component
public class AUserDaoImp implements AUserDao{
    @Override
    public void add() {
        System.out.println("執行新增操作");
    }

    @Override
    public void delete() {
        System.out.println("刪除");
    }

    @Override
    public void update() {
        System.out.println("更新");
    }

    @Override
    public void select() {
        System.out.println("查詢");
    }

    @Override
    public void insert() {
        System.out.println("插入");
    }
}

Spring使用的註解大全和解釋

註解 解釋
@Controller 組合註解(組合了@Component註解),應用在MVC層(控制層),DispatcherServlet會自動掃描註解了此註解的類,然後將web請求對映到註解了@RequestMapping的方法上。
@Service 組合註解(組合了@Component註解),應用在service層(業務邏輯層)
@Reponsitory 組合註解(組合了@Component註解),應用在dao層(資料訪問層)
@Component 表示一個帶註釋的類是一個“元件”,成為Spring管理的Bean。當使用基於註解的配置和類路徑掃描時,這些類被視為自動檢測的候選物件。同時@Component還是一個元註解。
@Autowired Spring提供的工具(由Spring的依賴注入工具(BeanPostProcessor、BeanFactoryPostProcessor)自動注入。)
@Resource JSR-250提供的註解
@Inject JSR-330提供的註解
@Configuration 聲明當前類是一個配置類(相當於一個Spring配置的xml檔案)
@ComponentScan 自動掃描指定包下所有使用@Service,@Component,@Controller,@Repository的類並註冊
@Bean 註解在方法上,聲明當前方法的返回值為一個Bean。返回的Bean對應的類中可以定義init()方法和destroy()方法,然後在@Bean(initMethod=”init”,destroyMethod=”destroy”)定義,在構造之後執行init,在銷燬之前執行destroy。
@Aspect 宣告一個切面(就是說這是一個額外功能)
@After 後置建言(advice),在原方法前執行。
@Before 前置建言(advice),在原方法後執行。
@Around 環繞建言(advice),在原方法執行前執行,在原方法執行後再執行(@Around可以實現其他兩種advice)
@PointCut 宣告切點,即定義攔截規則,確定有哪些方法會被切入
@Transactional 宣告事務(一般預設配置即可滿足要求,當然也可以自定義)
@Cacheable 宣告資料快取
@EnableAspectJAutoProxy 開啟Spring對AspectJ的支援
@Value 值得注入。經常與Sping EL表示式語言一起使用,注入普通字元,系統屬性,表示式運算結果,其他Bean的屬性,檔案內容,網址請求內容,配置檔案屬性值等等
@PropertySource 指定檔案地址。提供了一種方便的、宣告性的機制,用於向Spring的環境新增PropertySource。與@configuration類一起使用。
@PostConstruct 標註在方法上,該方法在建構函式執行完成之後執行。
@PreDestroy 標註在方法上,該方法在物件銷燬之前執行。
@Profile 表示當一個或多個指定的檔案是活動的時,一個元件是有資格註冊的。使用@Profile註解類或者方法,達到在不同情況下選擇例項化不同的Bean。@Profile(“dev”)表示為dev時例項化。
@EnableAsync 開啟非同步任務支援。註解在配置類上。
@Async 註解在方法上標示這是一個非同步方法,在類上標示這個類所有的方法都是非同步方法。
@EnableScheduling 註解在配置類上,開啟對計劃任務的支援。
@Scheduled 註解在方法上,宣告該方法是計劃任務。支援多種型別的計劃任務:cron,fixDelay,fixRate
@Conditional 根據滿足某一特定條件建立特定的Bean
@Enable* 通過簡單的@Enable來開啟一項功能的支援。所有@Enable註解都有一個@Import註解,@Import是用來匯入配置類的,這也就意味著這些自動開啟的實現其實是匯入了一些自動配置的Bean(1.直接匯入配置類2.依據條件選擇配置類3.動態註冊配置類)
@RunWith 這個是Junit的註解,springboot集成了junit。一般在測試類裡使用:@RunWith(SpringJUnit4ClassRunner.class) — SpringJUnit4ClassRunner在JUnit環境下提供Sprng TestContext Framework的功能
@ContextConfiguration 用來載入配置ApplicationContext,其中classes屬性用來載入配置類:@ContextConfiguration(classes = {TestConfig.class(自定義的一個配置類)})
@ActiveProfiles 用來宣告活動的profile–@ActiveProfiles(“prod”(這個prod定義在配置類中))
@EnableWebMvc 用在配置類上,開啟SpringMvc的Mvc的一些預設配置:如ViewResolver,MessageConverter等。同時在自己定製SpringMvc的相關配置時需要做到兩點:1.配置類繼承WebMvcConfigurerAdapter類2.就是必須使用這個@EnableWebMvc註解。
@RequestMapping 用來對映web請求(訪問路徑和引數),處理類和方法的。可以註解在類和方法上,註解在方法上的@RequestMapping路徑會繼承註解在類上的路徑。同時支援Serlvet的request和response作為引數,也支援對request和response的媒體型別進行配置。其中有value(路徑),produces(定義返回的媒體型別和字符集),method(指定請求方式)等屬性。
@ResponseBody 將返回值放在response體內。返回的是資料而不是頁面
@RequestBody 允許request的引數在request體中,而不是在直接連結在地址的後面。此註解放置在引數前。
@PathVariable 放置在引數前,用來接受路徑引數。
@RestController 組合註解,組合了@Controller和@ResponseBody,當我們只開發一個和頁面互動資料的控制層的時候可以使用此註解。
@ControllerAdvice 用在類上,宣告一個控制器建言,它也組合了@Component註解,會自動註冊為Spring的Bean。
@ExceptionHandler 用在方法上定義全域性處理,通過他的value屬性可以過濾攔截的條件:@ExceptionHandler(value=Exception.class)–表示攔截所有的Exception。
@ModelAttribute 將鍵值對新增到全域性,所有註解了@RequestMapping的方法可獲得次鍵值對(就是在請求到達之前,往model裡addAttribute一對name-value而已)。
@InitBinder 通過@InitBinder註解定製WebDataBinder(用在方法上,方法有一個WebDataBinder作為引數,用WebDataBinder在方法內定製資料繫結,例如可以忽略request傳過來的引數Id等)。
@WebAppConfiguration 一般用在測試上,註解在類上,用來宣告載入的ApplicationContext是一個WebApplicationContext。他的屬性指定的是Web資源的位置,預設為src/main/webapp,我們可以修改為:@WebAppConfiguration(“src/main/resources”)。
@EnableAutoConfiguration 此註釋自動載入應用程式所需的所有Bean——這依賴於Spring Boot在類路徑中的查詢。該註解組合了@Import註解,@Import註解匯入了EnableAutoCofigurationImportSelector類,它使用SpringFactoriesLoader.loaderFactoryNames方法來掃描具有META-INF/spring.factories檔案的jar包。而spring.factories裡聲明瞭有哪些自動配置。
@SpingBootApplication SpringBoot的核心註解,主要目的是開啟自動配置。它也是一個組合註解,主要組合了@Configurer,@EnableAutoConfiguration(核心)和@ComponentScan。可以通過@SpringBootApplication(exclude={想要關閉的自動配置的類名.class})來關閉特定的自動配置。
@ImportResource 雖然Spring提倡零配置,但是還是提供了對xml檔案的支援,這個註解就是用來載入xml配置的。例:@ImportResource({“classpath
@ConfigurationProperties 將properties屬性與一個Bean及其屬性相關聯,從而實現型別安全的配置。例:@ConfigurationProperties(prefix=”authot”,locations={“classpath
@ConditionalOnBean 條件註解。當容器裡有指定Bean的條件下。
@ConditionalOnClass 條件註解。當類路徑下有指定的類的條件下。
@ConditionalOnExpression 條件註解。基於SpEL表示式作為判斷條件。
@ConditionalOnJava 條件註解。基於JVM版本作為判斷條件。
@ConditionalOnJndi 條件註解。在JNDI存在的條件下查詢指定的位置。
@ConditionalOnMissingBean 條件註解。當容器裡沒有指定Bean的情況下。
@ConditionalOnMissingClass 條件註解。當類路徑下沒有指定的類的情況下。
@ConditionalOnNotWebApplication 條件註解。當前專案不是web專案的條件下。
@ConditionalOnResource 條件註解。類路徑是否有指定的值。
@ConditionalOnSingleCandidate 條件註解。當指定Bean在容器中只有一個,後者雖然有多個但是指定首選的Bean。
@ConditionalOnWebApplication 條件註解。當前專案是web專案的情況下。
@EnableConfigurationProperties 註解在類上,宣告開啟屬性注入,使用@Autowired注入。例:@EnableConfigurationProperties(HttpEncodingProperties.class)。
@AutoConfigureAfter 在指定的自動配置類之後再配置。例:@AutoConfigureAfter(WebMvcAutoConfiguration.class)