Spring:Spring注解大全


 @Controller

標識一個該類是Spring MVC controller處理器,用來創建處理http請求的對象.

@Controller
public class TestController {
        @RequestMapping("/test")
        public String test(Map<String,Object> map){

            return "hello";
        }
}

 

@RestController

Spring4之后加入的注解,原來在@Controller中返回json需要@ResponseBody來配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默認返回json格式。

@RestController
public class TestController {
        @RequestMapping("/test")
        public String test(Map<String,Object> map){

            return "hello";
        }
}

 

@Service

用於標注業務層組件,以注解的方式把這個類注入到spring配置中

@Service
public class TestService {
        public String test(Map<String,Object> map){
            return "hello";
        }
}

 

@Autowired

用來裝配bean,都可以寫在字段上,或者方法上。
默認情況下必須要求依賴對象必須存在,如果要允許null值,可以設置它的required屬性為false,例如:@Autowired(required=false)

@RestController
public class TestController {

        @Autowired(required=false)
        private TestService service;

        @RequestMapping("/test")
        public String test(Map<String,Object> map){

            return "hello";
        }
}

 

@RequestMapping

類定義處: 提供初步的請求映射信息,相對於 WEB 應用的根目錄。
方法處: 提供進一步的細分映射信息,相對於類定義處的 URL。(還有許多屬性參數,不細講,可自行查找)

@RestController
public class TestController {
        @RequestMapping("/test")
        public String test(Map<String,Object> map){

            return "hello";
        }
}

 

@RequestParam

用於將請求參數區數據映射到功能處理方法的參數上,其中course_id就是接口傳遞的參數,id就是映射course_id的參數名,也可以不寫value屬性

public Resp test(@RequestParam(value="course_id") Integer id){
        return Resp.success(customerInfoService.fetch(id));
    }

 

@NonNull

標注在方法、字段、參數上,表示對應的值可以為空。

public class Student {
    @NonNull
    private Integer age;
    private String name;

    public void setAge(Integer age){
       this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

}

 

@Nullable

標注在方法、字段、參數上,表示對應的值不能為空。

public class Student {
    @Nullable
    private Integer age;
    private String name;

    public void setAge(Integer age){
       this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

}

 

@Resource(等同於@Autowired)

 @Autowired按byType自動注入,而@Resource默認按 byName自動注入,@Resource有兩個屬性是比較重要的,分是name和type,Spring將@Resource注解的name屬性解析為bean的名字,而type屬性則解析為bean的類型。所以如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不指定name也不指定type屬性,這時將通過反射機制使用byName自動注入策略。

如果同時指定了name和type,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則拋出異常
如果指定了name,則從上下文中查找名稱(id)匹配的bean進行裝配,找不到則拋出異常
如果指定了type,則從上下文中找到類型匹配的唯一bean進行裝配,找不到或者找到多個,都會拋出異常
如果既沒有指定name,又沒有指定type,則自動按照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>
@Resource(name= " student1")
private Student student ;

@Resource(type= "student2")

public void setSpellChecker( Studentstudent){ 
    this.Student= student; 
}

示例: 

第一個實現類

第二個實現類

使用name指定使用哪個實現類

@resource注入

 

@Qualifier

當一個接口有多個實現類時,就可以用此注解表明哪個實現類才是我們所需要的,名稱為我們之前定義@Service注解的名稱之一。

//接口類
public interface TestService{}

//實現類1
@Service("service1")
public class TestServiceImpl1 implements TestService{} //實現類2
@Service("service2")
public class TestServiceImpl2 implements TestService{}
//測試
@Autowired
@Qualifier("service1")
private TestService testService;

 

@Component

把普通pojo實例化到spring容器中,相當於配置文件中的 <bean id="" class=""/>
它泛指各種組件,就是說當我們的類不屬於各種歸類的時候(不屬於@Controller、@Services等的時候),我們就可以使用@Component來標注這個類。
此外,被@controller 、@service、@repository 、@component 注解的類,都會把這些類納入進spring容器中進行管理

@Component
public class TestClass {
        public String test(Map<String,Object> map){
            return "hello";
        }
}

 

@Repository

作用為給bean在容器中命名

定義一個接口

public interface UserRepository {
    void save();
}

兩個實現類

package com.proc.bean.repository;
 
import org.springframework.stereotype.Repository;
 
//將此UserRepositoryImps類在容器中命名改為userRepository
@Repository("userRepository")
public class UserRepositoryImps implements UserRepository{
 
    @Override
    public void save() {
        System.out.println("UserRepositoryImps save");
    }
}
package com.proc.bean.repository;
 
import org.springframework.stereotype.Repository;
 
//這個實現類則不進行命名
@Repository
public class UserJdbcImps implements UserRepository {
 
    @Override
    public void save() {
        System.out.println("UserJdbcImps save");
    }
}

調用接口測試:

@Autowired
 
private UserRepository userRepository;

//會找到我們命名為userRepository的bean,並裝配到userRepository中

 

@Scope

@Scope注解是springIoc容器中的一個作用域,在 Spring IoC 容器中具有以下幾種作用域:基本作用域singleton(單例)prototype(多例),Web 作用域(reqeust、session、globalsession),自定義作用域。(@Scope注解默認的singleton單例模式

prototype原型模式:
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)這個是說在每次注入的時候回自動創建一個新的bean實例

singleton單例模式:
@Scope(value=ConfigurableBeanFactory.SCOPE_SINGLETON)單例模式,在整個應用中只能創建一個實例

globalsession模式:
@Scope(value=WebApplicationContext.SCOPE_GLOBAL_SESSION)全局session中的一般不常用

@Scope(value
=WebApplicationContext.SCOPE_APPLICATION)在一個web應用中只創建一個實例 request模式: @Scope(value=WebApplicationContext.SCOPE_REQUEST)在一個請求中創建一個實例 session模式: @Scope(value=WebApplicationContext.SCOPE_SESSION)每次創建一個會話中創建一個實例
/**
     * 定義一個bean對象
     * @return
     */
    @Scope(value=ConfigurableBeanFactory.SCOPE_SINGLETON)
    @Bean(value="user0",name="user0",initMethod="initUser",destroyMethod="destroyUser")
    public User getUser(){
        System.out.println("創建user實例");
        return new User("張三",26);
    }

 

@Bean

產生一個bean的方法,並且交給Spring容器管理,相當於配置文件中的 <bean id="" class=""/>

@Bean
public class UserTest(){
public User getUser(){ System.out.println("創建user實例"); return new User("張三",26); }
}

 

@Transactional 

事務管理一般有編程式和聲明式兩種,編程式是直接在代碼中進行編寫事物處理過程,而聲名式則是通過注解方式或者是在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:tx="http://www.springframework.org/schema/tx"
       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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

JDBC事務

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
 </bean>

<tx:annotation-driven transaction-manager="transactionManager" />

Hibernate事務

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
<tx:annotation-driven transaction-manager="transactionManager" />

JPA事務

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
<tx:annotation-driven transaction-manager="transactionManager" />

Java原生API事務

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="transactionManagerName" value="java:/TransactionManager" />
    </bean>
<tx:annotation-driven transaction-manager="transactionManager" />

spring所有的事務管理策略類都繼承自org.springframework.transaction.PlatformTransactionManager接口

 

@Aspect

作用是標記一個切面類(spring不會將切面注冊為Bean也不會增強,但是需要掃描)

<!-- 掃描Aspect增強的類 -->
<context:component-scan base-package="">
    <context:include-filter type="annotation"
        expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>

<!-- 開啟@AspectJ注解支持 -->
<aop:aspectj-autoproxy/>

<?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"
         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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--包掃描-->
<context:component-scan base-package="com.cn"/> <!--開啟ioc注解--> <context:annotation-config/> <!--開啟aop注解--> <aop:aspectj-autoproxy/>
 </beans>

 

@Pointcut

定義切點,切點表達式(execution(權限訪問符 返回值類型 方法所屬的類名包路徑.方法名(形參類型) 異常類型))

@Aspect
@Component
public class AfterThrowingAspect { //全路徑execution(public String com.cnblogs.hellxz.test.Test.access(String,String)) @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))") public void pointcut() {} ....... }

 

@Before

前置增強,配合@Pointcut一起使用

 

@Aspect
@Component
public class AfterThrowingAspect { //全路徑execution(public String com.cnblogs.hellxz.test.Test.access(String,String)) @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))") public void pointcut() {} //前置增強 @Before("pointcut()") public void before(JoinPoint jp){ System.out.println("我是方法"+jp.getSignature().getName()+"的前置增強!"); } }

 

 
        

@AfterReturning

后置增強,配合@Pointcut一起使用

 

@Aspect
@Component
public class AfterThrowingAspect {

    //全路徑execution(public String com.cnblogs.hellxz.test.Test.access(String,String))
    @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))")
    public void pointcut() {}
     
    //前置增強
    @Before("pointcut()")
    public void before(JoinPoint jp){
        System.out.println("我是方法"+jp.getSignature().getName()+"的前置增強!");      
    }

     //后置增強
     @AfterReturning(value = "pointcut()",returning = "obj")
     public void afterReturning(JoinPoint jp,Object obj){
         System.out.println("我是方法"+jp.getSignature().getName()+"的后置增強!"+",返回值為"+obj);
     }


}

 

 

@Around

環繞增強,配合@Pointcut一起使用

 

@Aspect
@Component
public class AfterThrowingAspect {

    //全路徑execution(public String com.cnblogs.hellxz.test.Test.access(String,String))
    @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))")
    public void pointcut() {}
     
    //前置增強
    @Before("pointcut()")
    public void before(JoinPoint jp){
        System.out.println("我是方法"+jp.getSignature().getName()+"的前置增強!");      
    }

     //后置增強
     @AfterReturning(value = "pointcut()",returning = "obj")
     public void afterReturning(JoinPoint jp,Object obj){
         System.out.println("我是方法"+jp.getSignature().getName()+"的后置增強!"+",返回值為"+obj);
     }

     //環繞增強
     @Around("pointcut()")
     public void around(ProceedingJoinPoint jp) throws Throwable {
         System.out.println("我是環繞增強中的前置增強!");
         Object proceed = jp.proceed();//植入目標方法
         System.out.println("我是環繞增強中的后置增強!");
     }


}

 

 

@AfterThrowing

異常拋出增強,配合@Pointcut一起使用

 

@Aspect
@Component
public class AfterThrowingAspect {

    //全路徑execution(public String com.cnblogs.hellxz.test.Test.access(String,String))
    @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))")
    public void pointcut() {}
     
    //前置增強
    @Before("pointcut()")
    public void before(JoinPoint jp){
        System.out.println("我是方法"+jp.getSignature().getName()+"的前置增強!");      
    }

     //后置增強
     @AfterReturning(value = "pointcut()",returning = "obj")
     public void afterReturning(JoinPoint jp,Object obj){
         System.out.println("我是方法"+jp.getSignature().getName()+"的后置增強!"+",返回值為"+obj);
     }

     //環繞增強
     @Around("pointcut()")
     public void around(ProceedingJoinPoint jp) throws Throwable {
         System.out.println("我是環繞增強中的前置增強!");
         Object proceed = jp.proceed();//植入目標方法
         System.out.println("我是環繞增強中的后置增強!");
     }

     //異常拋出增強
     @AfterThrowing(value = "pointcut()",throwing = "e")
     public void error(JoinPoint jp,Exception e){
         System.out.println("我是異常拋出增強"+",異常為:"+e.getMessage());
     }


}

 

 

@After

最終增強(最后執行),配合@Pointcut一起使用

 

@Aspect
@Component
public class AfterThrowingAspect {

    //全路徑execution(public String com.cnblogs.hellxz.test.Test.access(String,String))
    @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))")
    public void pointcut() {}
     
    //前置增強
    @Before("pointcut()")
    public void before(JoinPoint jp){
        System.out.println("我是方法"+jp.getSignature().getName()+"的前置增強!");      
    }

     //后置增強
     @AfterReturning(value = "pointcut()",returning = "obj")
     public void afterReturning(JoinPoint jp,Object obj){
         System.out.println("我是方法"+jp.getSignature().getName()+"的后置增強!"+",返回值為"+obj);
     }

     //環繞增強
     @Around("pointcut()")
     public void around(ProceedingJoinPoint jp) throws Throwable {
         System.out.println("我是環繞增強中的前置增強!");
         Object proceed = jp.proceed();//植入目標方法
         System.out.println("我是環繞增強中的后置增強!");
     }

     //異常拋出增強
     @AfterThrowing(value = "pointcut()",throwing = "e")
     public void error(JoinPoint jp,Exception e){
         System.out.println("我是異常拋出增強"+",異常為:"+e.getMessage());
     }

     //最終增強
     @After("pointcut()")
     public void after(JoinPoint jp){
         System.out.println("我是最終增強");
     }
}

 

 

@Cacheable(結合Redis搭建緩存機制)

*重點 單獨一篇文章講解

用來標記緩存查詢。可用用於方法或者類中。(簡介)

當標記在一個方法上時表示該方法是支持緩存的,
當標記在一個類上時則表示該類所有的方法都是支持緩存的。

 

@CacheEvict

*重點 單獨一篇文章講解

用來標記要清空緩存的方法,當這個方法被調用后,即會清空緩存。@CacheEvict(value=”UserCache”)

 

@Required(注釋檢查)

適用於bean屬性setter方法,並表示受影響的bean屬性必須在XML配置文件在配置時進行填充。否則,容器會拋出一個BeanInitializationException異常。

通俗的講:該注解放在setter方法上,表示當前的setter修飾的屬性必須在Spring.xml中進行裝配,否則報錯BeanInitializationException異常,所以這是個檢查注解。

public class Student {
    private Integer age;
    private String name;

    public Integer getAge() {
        return age;
    }

    @Required     //該注釋放在的是set方法中,如果沒有在xml配置文件中配置相關的屬性,就會報錯
    public void setAge(Integer age) {
        this.age = age;
    }
}
<?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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>
    <!-- student bean的定義 -->
    <bean id = "student" class="com.how2java.w3cschool.required.Student">
        <property name = "name" value="派大星"/>
        <!-- 這里沒有裝配age屬性,所以項目運行會報錯 -->
    </bean>
    
</beans>
報錯:“ Property 'age' is required for bean 'student' ”

 

@ModelAttribute

所有方法在調用前,先執行此@ModelAttribute方法.

 

A.標注在有返回值的方法上

當ModelAttribute設置了value,方法返回的值會以這個value為key以參數接受到的值作為這個key對應的value,組成k-v鍵值對,存入到Model中,如下面的方法執行之后,最終相當於 model.addAttribute(“user_name”, name);假如 @ModelAttribute沒有自定義value,則相當於
model.addAttribute(“name”, name);

往前台傳數據,可以傳對象,可以傳List,通過el表達式 ${}可以獲取到,

類似於request.setAttribute("sts",sts)效果一樣。

@ModelAttribute(value="user_name")
    public String before2(@RequestParam(required = false) String name, Model model) {
        System.out.println("進入了2:" + name);
        return name;
    }

B.標注在沒有返回值的方法上

需要手動model.add方法

@ModelAttribute
    public void before(@RequestParam(required = false) Integer age, Model model){
        model.addAttribute("age", age);
        System.out.println("進入了1:" + age);
}

C.標注在方法的參數上

會將客戶端傳遞過來的參數按名稱注入到指定對象中,並且會將這個對象自動加入ModelMap中,便於View層使用.

@RequestMapping(value="/mod2")
     public Resp mod2(@ModelAttribute("user_name") String user_name, 
             @ModelAttribute("name") String name,
             @ModelAttribute("age") Integer age,Model model){
         System.out.println("進入mod2");
         System.out.println("user_name:"+user_name);
         System.out.println("name:"+name);
         System.out.println("age:"+age);
         System.out.println("model:"+model);
        return Resp.success("1");
    }

 

 

文章轉載至:https://blog.csdn.net/weixin_41990707/article/details/82292323

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM