spring springboot springcloud常用注解
@SpringBootApplication
組合注解,用在啟動類上,源碼:
@Retention(RetentionPolicy.RUNTIME)
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication
========================
@SpringBootConfiguration
@Configuration
public @interface SpringBootConfiguration
SpringBootConfiguration標注這個類是一個配置類,是@Configuration注解的派生注解,和@Configuration注解的功能一致,標注這個類是一個配置類,并會將當前類內聲明的一個或多個以@Bean注解標記的方法的實例納入到spring容器中,并且實例名就是方法名。
只不過@SpringBootConfiguration是springboot的注解,而@Configuration是spring的注解,關于@Configuration注解,更詳細的,可以參看《spring注解 @Conditional的使用》
https://blog.csdn.net/qq_28410283/article/details/91353603
--------------------------------------------?
@EnableAutoConfiguration
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration
一般加在主類上,通過此注解,能所有符合自動配置條件的bean的定義加載到spring容器中。
自動載入應用程序所需的所有Bean——這依賴于Spring Boot在類路徑中的查找。
從classpath中搜索所有META-INF/spring.factories配置文件然后,將其中org.springframework.boot.autoconfigure.EnableAutoConfiguration key對應的配置項加載到spring容器
只有spring.boot.enableautoconfiguration為true(默認為true)的時候,才啟用自動配置
https://blog.csdn.net/l18848956739/article/details/100692163
Spring中也有一種類似與Java SPI的加載機制。它在META-INF/spring.factories文件中配置接口的實現類名稱,然后在程序中讀取這些配置文件并實例化。這種自定義的SPI機制是Spring Boot Starter實現的基礎。
https://blog.csdn.net/lldouble/article/details/80690446
?
@EnableAutoConfiguration注解原理
從classpath中搜索所有META-INF/spring.factories配置文件然后,將其中org.springframework.boot.autoconfigure.EnableAutoConfiguration key對應的配置項加載到spring容器
只有spring.boot.enableautoconfiguration為true(默認為true)的時候,才啟用自動配置
@EnableAutoConfiguration還可以進行排除,排除方式有2中,一是根據class來排除(exclude),二是根據class name(excludeName)來排除
其內部實現的關鍵點有
1)ImportSelector 該接口的方法的返回值都會被納入到spring容器管理中
2)SpringFactoriesLoader 該類可以從classpath中搜索所有META-INF/spring.factories配置文件,并讀取配置
https://www.jianshu.com/p/1fba2f40f7b6
--------------------------------------------?
@Configuration
@Component
public @interface Configuration
用于定義配置類,@Configuation等價于<Beans></Beans>,可替換xml配置文件,被注解的類內部包含有一個或多個被@Bean注解的方法,這些方法將會被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext類進行掃描,并用于構建bean定義,初始化Spring容器。
?
@Configuration 和 @Component 區別
實際上表現為@Configuration+@bean和@Component+@bean的區別
一句話概括就是 @Configuration 中所有帶 @Bean 注解的方法都會被動態代理,因此調用該方法返回的都是同一個實例。
從定義來看, @Configuration 注解本質上還是 @Component,雖然Component注解也會當做配置類,但是并不會為其生成CGLIB代理Class。
Spring 容器在啟動時,會加載默認的一些 PostPRocessor,其中就有 ConfigurationClassPostProcessor,這個后置處理程序專門處理帶有 @Configuration 注解的類,這個程序會在 bean 定義加載完成后,在 bean 初始化前進行處理。主要處理的過程就是使用 cglib 動態代理增強類,而且是對其中帶有 @Bean 注解的方法進行處理。
@Component 注解并沒有通過 cglib 來代理@Bean 方法的調用。有些特殊情況下,我們不希望 MyBeanConfig 被代理(代理后會變成WebMvcConfig$$EnhancerBySpringCGLIB$$8bef3235293)時,就得用 @Component。
https://blog.csdn.net/isea533/article/details/78072133
?
當使用Configuration注解時,生成當前對象的子類Class,并對方法攔截,第二次調用方法時直接從BeanFactory之中獲取對象,所以得到的是同一個對象。https://blog.csdn.net/long476964/article/details/80626930
透過現象看原理:詳解Spring中Bean的this調用導致AOP失效的原因
在Spring提供的@Configuration配置類中,就有這種場景的應用,可以看到c1和c2是同一個對象引用,而不是每次調用方法都new一個新的對象。
-------------------------------------------
@Bean
@Bean是一個方法級別上的注解,主要用在@Configuration注解的類里,也可以用在@Component注解的類里。
https://www.cnblogs.com/feiyu127/p/7700090.html
@Component 和 @Bean 的區別
@Component(和@Service和@Repository)用于自動檢測和使用類路徑掃描自動配置bean。注釋類和bean之間存在隱式的一對一映射(即每個類一個bean)。
這種方法對需要進行邏輯處理的控制非常有限,因為它純粹是聲明性的。
@Bean用于顯式聲明單個bean,而不是讓Spring像上面那樣自動執行它。它將bean的聲明與類定義分離,并允許您精確地創建和配置bean。
而@Bean則常和@Configuration注解搭配使用。
如果想將第三方的類變成組件,你又沒有沒有源代碼,也就沒辦法使用@Component進行自動配置,這種時候使用@Bean就比較合適了。
https://www.jianshu.com/p/67ed3bdc215c
https://blog.csdn.net/w605283073/article/details/89221522
Spring中的@Bean是否一定要與@Configuration一起用?
使用@Configuration注解,此時調用方法返回的是被Spring管理的單例Bean。
如果換做是@Component 注解,那么調用了方法返回的對象是執行這個方法返回的對象實例,而不是被spring管理的對象。
這就是差別所在。
https://blog.csdn.net/weixin_42749765/article/details/87098790
https://segmentfault.com/a/1190000014119872?utm_source=tag-newest
?
作用對象不同: @Component 注解作用于類,而 @Bean 注解作用于方法;
?@Component 通常是通過類路徑掃描來自動偵測,以及自動裝配到 Spring 容器中(可以使用 @ComponentScan注解定義要掃描的路徑,從中找出標識了需要裝配的類,并自動裝配到 Spring 的 bean 容器中)。
@Bean 注解通常是在標有該注解的方法中定義產生這個 bean,@Bean告訴了 Spring 這是某個類的示例,當需要用到它的時候還給我;
?@Bean 注解比 Component 注解的更靈活,而且很多地方我們只能通過 @Bean 注解來注冊 bean。比如當我們引用第三方庫中的類需要裝配到 Spring容器時,則只能通過 @Bean來實現。
https://cloud.tencent.com/developer/article/1512755
----------------------------------------
@Scope
@Scope默認是單例模式,即scope="singleton"。
另外scope還有prototype、request、session、global session作用域。scope="prototype"多例
https://blog.csdn.net/tzbugs/article/details/82142286
?
@Lazy懶加載
//默認是單實例的/*** ConfigurableBeanFactory#SCOPE_PROTOTYPE * @see ConfigurableBeanFactory#SCOPE_SINGLETON * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST request* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION sesssion* @return\* @Scope:調整作用域* prototype:多實例的:ioc容器啟動并不會去調用方法創建對象放在容器中。* 每次獲取的時候才會調用方法創建對象;* singleton:單實例的(默認值):ioc容器啟動會調用方法創建對象放到ioc容器中。* 以后每次獲取就是直接從容器(map.get())中拿,* request:同一次請求創建一個實例* session:同一個session創建一個實例* * 懶加載:* 單實例bean:默認在容器啟動的時候創建對象;* 懶加載:容器啟動不創建對象。第一次使用(獲取)Bean創建對象,并初始化;* */@Lazy@Beanpublic UserLazy userLazy(){System.out.println("給容器中添加UserLazy");return new UserLazy("tomcat");}
----------------------------------------
@Component, @Repository, @Service區別
Component是一個通用的Spring容器管理的單例bean組件。而@Repository, @Service, @Controller就是針對不同的使用場景所采取的特定功能化的注解組件。
| 注解 | 含義 |
|---|---|
| @Component | 最普通的組件,可以被注入到spring容器進行管理 |
| @Repository | 作用于持久層 |
| @Service | 作用于業務邏輯層 |
| @Controller | 作用于表現層(spring-mvc的注解) |
有兩個注解是不能被其他注解所互換的:
@Controller?注解的bean會被spring-mvc框架所使用。@Repository?會被作為持久層操作(數據庫)的bean來使用
如果想使用自定義的組件注解,那么只要在你定義的新注解中加上@Component即可。
https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/whats-the-difference-between-component-repository-service-annotations-in.md
----------------------------------------
@ComponentScan
@Repeatable(ComponentScans.class)
public @interface ComponentScan {... ...String resourcePattern() default "**/*.class";... ...
}
組件掃描。如果掃描到有@Component @Controller @Service等這些注解的類,則把這些類注冊為bean。
//配置類==配置文件
@Configuration //告訴Spring這是一個配置類@ComponentScans(value = {@ComponentScan(value="com.demo",includeFilters = {
/* @Filter(type=FilterType.ANNOTATION,classes={Controller.class}),@Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class}),*/@Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})},useDefaultFilters = false) })
//@ComponentScan value:指定要掃描的包
//excludeFilters = Filter[] :指定掃描的時候按照什么規則排除那些組件
//includeFilters = Filter[] :指定掃描的時候只需要包含哪些組件
//FilterType.ANNOTATION:按照注解
//FilterType.ASSIGNABLE_TYPE:按照給定的類型;
//FilterType.ASPECTJ:使用ASPECTJ表達式
//FilterType.REGEX:使用正則指定
//FilterType.CUSTOM:使用自定義規則
public class MainConfig {//給容器中注冊一個Bean;類型為返回值的類型,id默認是用方法名作為id@Bean("user")public User user01(){return new User("Tom", 12);}}
----------------------------------------
@Import
注解可以把普通類導入到 IoC容器中
想要讓一個普通類接受 Spring 容器管理,有3種方法
- 使用 @Bean 注解
- 使用 @Controller @Service @Repository @Component 注解標注該類,然后再使用 @ComponentScan 掃描包
- @Import 方法
https://www.jianshu.com/p/afd2c49394c2
?
未用@componscan注解指定掃描的包時,默認掃描的是@import注解所在的包。
可以再次添加一個配置文件,在配置文件指定我們需要掃描的包,在代碼中加入邏輯:若@component不存在或未指定,則使用配置文件中指定的路徑進行掃描。
https://www.cnblogs.com/heliusKing/p/11774253.html
https://www.cnblogs.com/heliusKing/p/11372014.html
?
給容器中注冊組件;1)、包掃描+組件標注注解(@Controller/@Service/@Repository/@Component)[自己寫的類]2)、@Bean[導入的第三方包里面的組件]3)、@Import[快速給容器中導入一個組件]1)、@Import(要導入到容器中的組件);容器中就會自動注冊這個組件,id默認是全類名2)、ImportSelector:返回需要導入的組件的全類名數組;3)、ImportBeanDefinitionRegistrar:手動注冊bean到容器中4)、使用Spring提供的 FactoryBean(工廠Bean);1)、默認獲取到的是工廠bean調用getObject創建的對象2)、要獲取工廠Bean本身,我們需要給id前面加一個&&colorFactoryBean
Import注解在4.2之前只支持導入配置類 在4.2,@Import注解支持導入普通的java類,并將其聲明成一個bean。
https://cloud.tencent.com/developer/article/1455362
public class ImportDemo {public void doSomething () {System.out.println("ImportDemo.doSomething()");}
}@Configuration
@Import(ImportDemo.class)
public class ImportConfig {}public class ImportDemo {public void doSomething () {System.out.println("ImportDemo.doSomething()");}
}public class TestMain {public static void main(String[] args) {AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext("com.springboot.importtest");ImportDemo importDemo = context.getBean(ImportDemo.class);importDemo.doSomething();}}
在實例中使用,比如@Component
package com.paopaoedu.springboot.controller;import com.paopaoedu.springboot.service.ImportDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class TestController {@Autowiredprivate ImportDemo importDemo;@RequestMapping("/")public String sayHello() {return importDemo.doSomething();}
}
---------------------------------------
@ConditionalOnClass和ConditionalOnMissingBean
@ConditionalOnClass是Springboot實現自動配置的重要支撐之一。其用途是判斷當前classpath下是否存在指定類,若是則將當前的配置裝載入spring容器。https://blog.csdn.net/lucyTheSlayer/article/details/80430912
@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate對象了,這個自動配置的RedisTemplate不會實例化。因此我們可以直接自己寫個配置類,配置RedisTemplate。
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBeanpublic StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}}
https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html
=======================
@Value
三種方式
//使用@Value賦值;//1、基本數值//2、可以寫SpEL; #{}//3、可以寫${};取出配置文件【properties】中的值(在運行環境變量里面的值)@Value("TomCat")private String name;@Value("#{12-2}")private Integer age;@Value("${person.tomName}")private String tomName;
https://blog.csdn.net/a546835886/article/details/81287825
?
@Value一個一個注入,單個配置項
https://blog.csdn.net/clmmei_123/article/details/81871836
-------------------------------------
@ConfigurationProperties
想把配置文件的信息,讀取并自動封裝成實體類,批量注入配置文件中的屬性,多個配置項用一個配置類。
https://blog.csdn.net/yingxiake/article/details/51263071
--------------------------------------------
@Qualifier
在Controller中需要注入service那么我的這個server有兩個實現類如何區分開這兩個impl呢?
Qualifier的意思是合格者,通過這個標示,表明了哪個實現類才是我們所需要的,添加@Qualifier注解,需要注意的是@Qualifier的參數名稱為我們之前定義@Service注解的名稱之一。
使用@resource注入時比較簡單了注解自帶了“name”的val就是@Service注解的名稱之一。
https://blog.csdn.net/qq_36567005/article/details/80611139
Qualifier多數據源實現:
http://blog.didispace.com/springbootmultidatasource/
------------------------------------
@PropertySource
加載指定配置文件。
如果應用比較大的時候,如果所有的內容都當在一個文件中,如“application.properties”或者“application.yml”中時,就會顯得比較臃腫,同時也不太好理解和維護
可以將一個文件拆分為多個,此時使用@PropertySource即可解決問題。
https://blog.csdn.net/wangmx1993328/article/details/81005170
---------------------
@importSource
通過@importSource來加載.xml文件將配置加載到spring環境中
https://blog.csdn.net/abc_123456___/article/details/91126042
----------------------------
@EnableTransactionManagement
Spring Boot的事務管理注解@EnableTransactionManagement的使用
----------------------------------
@RefreshScope
是spring cloud提供的一種特殊的scope實現,用來實現配置、實例熱加載。
https://www.jianshu.com/p/188013dd3d02
需要熱加載的bean需要加上@RefreshScope注解,當配置發生變更的時候可以在不重啟應用的前提下完成bean中相關屬性的刷新。
https://blog.csdn.net/weixin_40318210/article/details/87954179
---------------------------------
@EnableDiscoveryClient和@EnableEurekaClient
共同點就是:都是能夠讓注冊中心能夠發現,掃描到改服務。
不同點:@EnableEurekaClient只適用于Eureka作為注冊中心,@EnableDiscoveryClient?可以是其他注冊中心。
https://blog.csdn.net/zheng199172/article/details/82466139
-----------------
@id
mongodb要注意,java class中增加一個id屬性,它會自動映射成"_id",如果數據庫中本來就是id,那么就讀不到了
https://www.cnblogs.com/zdkjob/p/10038746.html
---------------
@RestController
是Spring4之后加入的注解,原來在@Controller中返回json需要@ResponseBody來配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默認返回json格式。而@Controller是用來創建處理http請求的對象,一般結合@RequestMapping使用。
----------------------
@RequestMapping
RequestMapping是一個用來處理請求地址映射的注解,可用于類或方法上。用于類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。
https://www.cnblogs.com/Fooo/p/11724709.html
------------------
@PostConstruct
@PostContruct是spring框架的注解,在方法上加該注解會在項目啟動的時候執行該方法,也可以理解為在spring容器初始化的時候執行該方法。
@PostConstruct在項目中的用處
1.spring項目加載數據字典
@PostConstruct注解的方法在項目啟動的時候執行這個方法,也可以理解為在spring容器啟動的時候執行,可作為一些數據的常規化加載,比如數據字典之類的。
2.spring項目的定時任務
spring自帶的@schedule,沒有開關,項目啟動總會啟動一個線程;
做項目的時候就使用Java的timer,這個設置開關即可自由的控制,關閉的時候,不會啟動線程;
Java的timer也需要找到一個啟動類,可以放到main函數里面啟動,這樣的話,代碼的耦合性太高了,而使用PostConstruct是很干凈的。
spring中Constructor、@Autowired、@PostConstruct的順序
其實從依賴注入的字面意思就可以知道,要將對象p注入到對象a,那么首先就必須得生成對象p與對象a,才能執行注入。所以,如果一個類A中有個成員變量p被@Autowired注解,那么@Autowired注入是發生在A的構造方法執行完之后的。
如果想在生成對象時候完成某些初始化操作,而偏偏這些初始化操作又依賴于依賴注入,那么就無法在構造函數中實現。為此,可以使用@PostConstruct注解一個方法來完成初始化,@PostConstruct注解的方法將會在依賴注入完成后被自動調用。
Constructor >> @Autowired >> @PostConstruct
https://blog.csdn.net/qq_37636695/article/details/84791468
?
@PostConstruct和?@PreDestroy注解位于?java.xml.ws.annotation包是Java EE的模塊的一部分。J2EE已經在Java 9中被棄用,并且計劃在Java 11中刪除它
為pom.xml或build.gradle添加必要的依賴項
(Java 9+中的Spring @PostConstruct和@PreDestroy替代品)
https://blog.csdn.net/weixin_36048246/article/details/84394539
=========================
SpringBoot利用@WebFilter配置Filter
@WebFilter 用于將一個類聲明為過濾器,該注解將會在部署時被容器處理,容器將根據具體的屬性配置將相應的類部署為過濾器。該注解具有下表給出的一些常用屬性 ( 以下所有屬性均為可選屬性,但是 value、urlPatterns、servletNames 三者必需至少包含一個,且 value 和 urlPatterns 不能共存,如果同時指定,通常忽略 value 的取值 )?
https://www.cnblogs.com/ooo0/p/10360952.html
https://blog.csdn.net/With_Her/article/details/82627620
@WebFilter(filterName = "FilterDemo01", urlPatterns = { "/*" })
public class FilterDemo01 implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("----FilterDemo01過濾器初始化----");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;String servletPath = request.getServletPath();if (PATH_MATCHER.match("/admin/**", servletPath)) {AuthInfo authInfo = AuthUtil.getAuthInfo();if (authInfo == null) {log.error("403 Forbidden 禁止訪問>" + servletPath);writeForbidden(response);return;}}filterChain.doFilter(servletRequest, servletResponse);}@Overridepublic void destroy() {System.out.println("----過濾器銷毀----");}
}
使用@ControllerAdvice和@ExceptionHandler注解
在SpringBoot應用中使用統一異常處理
https://www.cnblogs.com/lgjlife/p/10988439.html
https://blog.csdn.net/hao_kkkkk/article/details/80538955
?
@ControllerAdvice
這是一個增強的 Controller。使用這個 Controller ,可以實現三個方面的功能:
全局異常處理
使用 @ControllerAdvice 實現全局異常處理,只需要定義類,添加該注解即可定義
@ExceptionHandler 注解用來指明異常的處理類型
全局數據綁定
全局數據綁定功能可以用來做一些初始化的數據操作,我們可以將一些公共的數據定義在添加了 @ControllerAdvice 注解的類中,這樣,在每一個 Controller 的接口中,就都能夠訪問導致這些數據。
使用 @ModelAttribute 注解標記該方法的返回數據是一個全局數據
全局數據預處理
兩個實體類都有一個 name 屬性,從前端傳遞時 ,無法區分。此時,通過 @ControllerAdvice 的全局數據預處理可以解決這個問題
https://www.cnblogs.com/lenve/p/10748453.html
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {@ResponseBody@ExceptionHandler(NullPointerException.class)public BaseResult globalException(HttpServletResponse response,NullPointerException ex){log.info("GlobalExceptionHandler...");
log.info("錯誤代碼:" + response.getStatus());
BaseResult result = new WebResult(WebResult.RESULT_FAIL,"request error:"+response.getStatus(),"GlobalExceptionHandler:"+ex.getMessage());return result;
}}
@ControllerAdvice和@RestControllerAdvice區別
如果全部異常處理返回json,那么可以使用 @RestControllerAdvice 代替 @ControllerAdvice ,這樣在方法上就可以不需要添加 @ResponseBody。
@RestControllerAdvice和@ControllerAdvice 類似于 @RestController 與 @Controller的區別
@RestControllerAdvice
https://blog.csdn.net/canfengli/article/details/88786339
https://blog.csdn.net/qq_35098526/article/details/88949425
package com.springboot.demo.common.exeception;import com.springboot.demo.common.enums.ResultStatusCode;
import com.springboot.demo.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;import javax.validation.ConstraintViolationException;
/*** 類描述: 全局異常攔截處理器* 1.處理自定義異常* 2.未知異常統一返回服務器錯誤* 3.已經catch到的異常不會被捕獲* 4.異常的體系結構中,哪個異常與目標方法拋出的異常血緣關系越緊密,就會被哪個捕捉到。* @see ExceptionHandler:統一處理某一類異常,從而能夠減少代碼重復率和復雜度* @see ControllerAdvice:異常集中處理,更好的使業務邏輯與異常處理剝離開* @see ResponseStatus:可以將某種異常映射為HTTP狀態碼 成功則Status Code: 200* @author licanfeng* @date 2019/3/11 16:13* @version 1.0*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {/*** 400 - Bad Request*/@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler({HttpMessageNotReadableException.class, MissingServletRequestParameterException.class, BindException.class,ServletRequestBindingException.class, MethodArgumentNotValidException.class, ConstraintViolationException.class})public Result handleHttpMessageNotReadableException(Exception e) {log.error("參數解析失敗", e);if (e instanceof BindException){return new Result(ResultStatusCode.BAD_REQUEST.getCode(), ((BindException)e).getAllErrors().get(0).getDefaultMessage());}return new Result(ResultStatusCode.BAD_REQUEST.getCode(), e.getMessage());}/*** 405 - Method Not Allowed* 帶有@ResponseStatus注解的異常類會被ResponseStatusExceptionResolver 解析*/@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)@ExceptionHandler(HttpRequestMethodNotSupportedException.class)public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {log.error("不支持當前請求方法", e);return new Result(ResultStatusCode.METHOD_NOT_ALLOWED, null);}/*** 其他全局異常在此捕獲* @param e* @return*/@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)@ExceptionHandler(Throwable.class)public Result handleException(Throwable e) {log.error("服務運行異常", e);if (e instanceof ShiroException) {return new Result(ResultStatusCode.UNAUTHO_ERROR);} else if (e instanceof JedisConnectionException) {//redis連接異常return new Result(ResultStatusCode.REDIS_CONNECT_ERROR);} else if (e instanceof JedisException) {//redis異常return new Result(ResultStatusCode.REDIS_ERROR);}return new Result(ResultStatusCode.SYSTEM_ERR, null);}}
?
總結
以上是生活随笔為你收集整理的spring springboot springcloud常用注解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黄山风景区有索道吗?价格多少?
- 下一篇: 互联网大厂技术面试内幕@霞落满天