javascript
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)
RequestMapping
類定義處: 提供初步的請求映射信息,相對于 WEB 應用的根目錄。
方法處: 提供進一步的細分映射信息,相對于類定義處的 URL。(還有許多屬性參數,不細講,可自行查找)
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 {@NonNullprivate 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 {@Nullableprivate 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方式進行裝配;如果沒有匹配,則回退為一個原始類型進行匹配,如果匹配則自動裝配
示例
@Service(value="MyServiceImplA") public class MyServiceImplA implements MyService@Service(value="MyServiceImplB") public class MyServiceImplB implements MyService@RestController() public class MyServiceController {@Resource(name="MyServiceImplB")private MyService myService; }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容器中,相當于配置文件中的
它泛指各種組件,就是說當我們的類不屬于各種歸類的時候(不屬于@Controller、@Services等的時候),我們就可以使用@Component來標注這個類。
此外,被@controller 、@service、@repository 、@component 注解的類,都會把這些類納入進spring容器中進行管理
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{@Overridepublic void save() {System.out.println("UserRepositoryImps save");} } package com.proc.bean.repository;import org.springframework.stereotype.Repository;//這個實現類則不進行命名 @Repository public class UserJdbcImps implements UserRepository {@Overridepublic void save() {System.out.println("UserJdbcImps save");} }調用接口測試:
@Autowiredprivate 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
產生一個bean的方法,并且交給Spring容器管理,相當于配置文件中的
@Beanpublic class UserTest(){public User getUser(){System.out.println("創建user實例");return new User("張三",26);}}Transactional
<?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搭建緩存機制)
用來標記緩存查詢。可用用于方法或者類中
- 用來標記緩存查詢。可用用于方法或者類中。- 當標記在一個方法上時表示該方法是支持緩存的,- 當標記在一個類上時則表示該類所有的方法都是支持緩存的。參數列表
| value | 名稱 | @Cacheable(value={”c1”,”c2”} |
| key | key | @Cacheable(value=”c1”,key=”#id”) |
| condition | 條件 | @Cacheable(value=”c1”,condition=”#id=1”) |
比如@Cacheable(value=”UserCache”) 標識的是當調用了標記了這個注解的方法時,邏輯默認加上從緩存中獲取結果的邏輯,如果緩存中沒有數據,則執行用戶編寫查詢邏輯,查詢成功之后,同時將結果放入緩存中。
但凡說到緩存,都是key-value的形式的,因此key就是方法中的參數(id),value就是查詢的結果,而命名空間UserCache是在spring*.xml中定義.
CacheEvict
用來標記要清空緩存的方法,當這個方法被調用后,即會清空緩存。@CacheEvict(value=”UserCache”)
參數列表
| value | 名稱 | @Cacheable(value={”c1”,”c2”} |
| key | key | @Cacheable(value=”c1”,key=”#id”) |
| condition | 緩存的條件,可以為空 | |
| allEntries | 是否清空所有緩存內容 | @CachEvict(value=”c1”,allEntries=true)) |
| beforeInvocation | 是否在方法執行前就清空 | @CachEvict(value=”c1”,beforeInvocation=true) |
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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://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
使用地方有三種:
標記在方法上,會在每一個@RequestMapping標注的方法前執行,如果有返回值,則自動將該返回值加入到ModelMap中。
A.在有返回的方法上:
當ModelAttribute設置了value,方法返回的值會以這個value為key,以參數接受到的值作為value,存入到Model中,如下面的方法執行之后,最終相當于 model.addAttribute(“user_name”, name);假如 @ModelAttribute沒有自定義value,則相當于
model.addAttribute(“name”, name);
B.標注在沒有返回值的方法上,需要手動model.add方法
@ModelAttributepublic 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");}總結
以上是生活随笔為你收集整理的Spring注解大全(示例详解)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css控制边界与边框示例(内边距、外边距
- 下一篇: 算法效率的度量方法