spring中那些讓你愛不釋手的代碼技巧

前言

最近愈來愈多的讀者承認個人文章,仍是件挺讓人高興的事情。有些讀者私信我說但願後面多分享spring方面的文章,這樣可以在實際工做中派上用場。正好我對spring源碼有過必定的研究,並結合我這幾年實際的工做經驗,把spring中我認爲不錯的知識點總結一下,但願對您有所幫助。git

一 如何獲取spring容器對象

1.實現BeanFactoryAware接口

`@Service`
`public class PersonService implements BeanFactoryAware {`
 `private BeanFactory beanFactory;`
 `@Override`
 `public void setBeanFactory(BeanFactory beanFactory) throws BeansException {`
 `this.beanFactory = beanFactory;`
 `}`
 `public void add() {`
 `Person person = (Person) beanFactory.getBean("person");`
 `}`
`}`
`複製代碼`

實現BeanFactoryAware接口,而後重寫setBeanFactory方法,就能從該方法中獲取到spring容器對象。github

2.實現ApplicationContextAware接口

`@Service`
`public class PersonService2 implements ApplicationContextAware {`
 `private ApplicationContext applicationContext;`
 `@Override`
 `public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {`
 `this.applicationContext = applicationContext;`
 `}`
 `public void add() {`
 `Person person = (Person) applicationContext.getBean("person");`
 `}`
`}`
`複製代碼`

實現ApplicationContextAware接口,而後重寫setApplicationContext方法,也能從該方法中獲取到spring容器對象。web

3.實現ApplicationListener接口

`@Service`
`public class PersonService3 implements ApplicationListener<ContextRefreshedEvent> {`
 `private ApplicationContext applicationContext;`
 `@Override`
 `public void onApplicationEvent(ContextRefreshedEvent event) {`
 `applicationContext = event.getApplicationContext();`
 `}`
 `public void add() {`
 `Person person = (Person) applicationContext.getBean("person");`
 `}`
`}`
`複製代碼`

實現ApplicationListener接口,須要注意的是該接口接收的泛型是ContextRefreshedEvent類,而後重寫onApplicationEvent方法,也能從該方法中獲取到spring容器對象。面試

此外,不得不提一下Aware接口,它實際上是一個空接口,裏面不包含任何方法。spring

它表示已感知的意思,經過這類接口能夠獲取指定對象,好比:緩存

  • 經過BeanFactoryAware獲取BeanFactory
  • 經過ApplicationContextAware獲取ApplicationContext
  • 經過BeanNameAware獲取BeanName等

Aware接口是很經常使用的功能,目前包含以下功能:springboot

二 如何初始化bean

spring中支持3種初始化bean的方法:服務器

  • xml中指定init-method方法
  • 使用@PostConstruct註解
  • 實現InitializingBean接口

第一種方法太古老了,如今用的人很少,具體用法就不介紹了。mybatis

1.使用@PostConstruct註解

`@Service`
`public class AService {`
 `@PostConstruct`
 `public void init() {`
 `System.out.println("===初始化===");`
 `}`
`}`
`複製代碼`

在須要初始化的方法上增長@PostConstruct註解,這樣就有初始化的能力。架構

2.實現InitializingBean接口

`@Service`
`public class BService implements InitializingBean {`
 `@Override`
 `public void afterPropertiesSet() throws Exception {`
 `System.out.println("===初始化===");`
 `}`
`}`
`複製代碼`

實現InitializingBean接口,重寫afterPropertiesSet方法,該方法中能夠完成初始化功能。

這裏順便拋出一個有趣的問題:init-methodPostConstructInitializingBean 的執行順序是什麼樣的?

決定他們調用順序的關鍵代碼在AbstractAutowireCapableBeanFactory類的initializeBean方法中。

這段代碼中會先調用BeanPostProcessor的postProcessBeforeInitialization方法,而PostConstruct是經過InitDestroyAnnotationBeanPostProcessor實現的,它就是一個BeanPostProcessor,因此PostConstruct先執行。

invokeInitMethods方法中的代碼:

決定了先調用InitializingBean,再調用init-method

因此得出結論,他們的調用順序是:

三 自定義本身的Scope

咱們都知道spring默認支持的Scope只有兩種:

  • singleton 單例,每次從spring容器中獲取到的bean都是同一個對象。
  • prototype 多例,每次從spring容器中獲取到的bean都是不一樣的對象。

spring web又對Scope進行了擴展,增長了:

  • RequestScope 同一次請求從spring容器中獲取到的bean都是同一個對象。
  • SessionScope 同一個會話從spring容器中獲取到的bean都是同一個對象。

即使如此,有些場景仍是沒法知足咱們的要求。

好比,咱們想在同一個線程中從spring容器獲取到的bean都是同一個對象,該怎麼辦?

這就須要自定義Scope了。

第一步實現Scope接口:

`public class ThreadLocalScope implements Scope {`
 `private static final ThreadLocal THREAD_LOCAL_SCOPE = new ThreadLocal();`
 `@Override`
 `public Object get(String name, ObjectFactory<?> objectFactory) {`
 `Object value = THREAD_LOCAL_SCOPE.get();`
 `if (value != null) {`
 `return value;`
 `}`
 `Object object = objectFactory.getObject();`
 `THREAD_LOCAL_SCOPE.set(object);`
 `return object;`
 `}`
 `@Override`
 `public Object remove(String name) {`
 `THREAD_LOCAL_SCOPE.remove();`
 `return null;`
 `}`
 `@Override`
 `public void registerDestructionCallback(String name, Runnable callback) {`
 `}`
 `@Override`
 `public Object resolveContextualObject(String key) {`
 `return null;`
 `}`
 `@Override`
 `public String getConversationId() {`
 `return null;`
 `}`
`}`
`複製代碼`

第二步將新定義的Scope注入到spring容器中:

`@Component`
`public class ThreadLocalBeanFactoryPostProcessor implements BeanFactoryPostProcessor {`
 `@Override`
 `public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {`
 `beanFactory.registerScope("threadLocalScope", new ThreadLocalScope());`
 `}`
`}`
`複製代碼`

第三步使用新定義的Scope:

`@Scope("threadLocalScope")`
`@Service`
`public class CService {`
 `public void add() {`
 `}`
`}`
`複製代碼`

四 別說FactoryBean沒用

提及FactoryBean就不得不提BeanFactory,由於面試官老喜歡問它們的區別。

  • BeanFactory:spring容器的頂級接口,管理bean的工廠。
  • FactoryBean:並不是普通的工廠bean,它隱藏了實例化一些複雜Bean的細節,給上層應用帶來了便利。

若是你看過spring源碼,會發現它有70多個地方在用FactoryBean接口。

上面這張圖足以說明該接口的重要性,請勿忽略它好嗎?

特別提一句:mybatisSqlSessionFactory對象就是經過SqlSessionFactoryBean類建立的。

咱們一塊兒定義本身的FactoryBean:

`@Component`
`public class MyFactoryBean implements FactoryBean {`
 `@Override`
 `public Object getObject() throws Exception {`
 `String data1 = buildData1();`
 `String data2 = buildData2();`
 `return buildData3(data1, data2);`
 `}`
 `private String buildData1() {`
 `return "data1";`
 `}`
 `private String buildData2() {`
 `return "data2";`
 `}`
 `private String buildData3(String data1, String data2) {`
 `return data1 + data2;`
 `}`
 `@Override`
 `public Class<?> getObjectType() {`
 `return null;`
 `}`
`}`
`複製代碼`

獲取FactoryBean實例對象:

`@Service`
`public class MyFactoryBeanService implements BeanFactoryAware {`
 `private BeanFactory beanFactory;`
 `@Override`
 `public void setBeanFactory(BeanFactory beanFactory) throws BeansException {`
 `this.beanFactory = beanFactory;`
 `}`
 `public void test() {`
 `Object myFactoryBean = beanFactory.getBean("myFactoryBean");`
 `System.out.println(myFactoryBean);`
 `Object myFactoryBean1 = beanFactory.getBean("&myFactoryBean");`
 `System.out.println(myFactoryBean1);`
 `}`
`}`
`複製代碼`
  • getBean("myFactoryBean");獲取的是MyFactoryBeanService類中getObject方法返回的對象,
  • getBean("&myFactoryBean");獲取的纔是MyFactoryBean對象。

五 輕鬆自定義類型轉換

spring目前支持3中類型轉換器:

  • Converter<S,T>:將 S 類型對象轉爲 T 類型對象
  • ConverterFactory<S, R>:將 S 類型對象轉爲 R 類型及子類對象
  • GenericConverter:它支持多個source和目標類型的轉化,同時還提供了source和目標類型的上下文,這個上下文能讓你實現基於屬性上的註解或信息來進行類型轉換。

這3種類型轉換器使用的場景不同,咱們以Converter<S,T>爲例。假如:接口中接收參數的實體對象中,有個字段的類型是Date,可是實際傳參的是字符串類型:2021-01-03 10:20:15,要如何處理呢?

第一步,定義一個實體User:

`@Data`
`public class User {`
 `private Long id;`
 `private String name;`
 `private Date registerDate;`
`}`
`複製代碼`

第二步,實現Converter接口:

`public class DateConverter implements Converter<String, Date> {`
 `private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");`
 `@Override`
 `public Date convert(String source) {`
 `if (source != null && !"".equals(source)) {`
 `try {`
 `simpleDateFormat.parse(source);`
 `} catch (ParseException e) {`
 `e.printStackTrace();`
 `}`
 `}`
 `return null;`
 `}`
`}`
`複製代碼`

第三步,將新定義的類型轉換器注入到spring容器中:

`@Configuration`
`public class WebConfig extends WebMvcConfigurerAdapter {`
 `@Override`
 `public void addFormatters(FormatterRegistry registry) {`
 `registry.addConverter(new DateConverter());`
 `}`
`}`
`複製代碼`

第四步,調用接口

`@RequestMapping("/user")`
`@RestController`
`public class UserController {`
 `@RequestMapping("/save")`
 `public String save(@RequestBody User user) {`
 `return "success";`
 `}`
`}`
`複製代碼`

請求接口時User對象中registerDate字段會被自動轉換成Date類型。

六 spring mvc攔截器,用過的都說好

spring mvc攔截器根spring攔截器相比,它裏面可以獲取HttpServletRequestHttpServletResponse 等web對象實例。

spring mvc攔截器的頂層接口是:HandlerInterceptor,包含三個方法:

  • preHandle 目標方法執行前執行
  • postHandle 目標方法執行後執行
  • afterCompletion 請求完成時執行

爲了方便咱們通常狀況會用HandlerInterceptor接口的實現類HandlerInterceptorAdapter類。

假若有權限認證、日誌、統計的場景,可使用該攔截器。

第一步,繼承HandlerInterceptorAdapter類定義攔截器:

`public class AuthInterceptor extends HandlerInterceptorAdapter {`
 `@Override`
 `public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)`
 `throws Exception {`
 `String requestUrl = request.getRequestURI();`
 `if (checkAuth(requestUrl)) {`
 `return true;`
 `}`
 `return false;`
 `}`
 `private boolean checkAuth(String requestUrl) {`
 `System.out.println("===權限校驗===");`
 `return true;`
 `}`
`}`
`複製代碼`

第二步,將該攔截器註冊到spring容器:

`@Configuration`
`public class WebAuthConfig extends WebMvcConfigurerAdapter {`
 
 `@Bean`
 `public AuthInterceptor getAuthInterceptor() {`
 `return new AuthInterceptor();`
 `}`
 `@Override`
 `public void addInterceptors(InterceptorRegistry registry) {`
 `registry.addInterceptor(getAuthInterceptor());`
 `}`
`}`
`複製代碼`

第三步,在請求接口時spring mvc經過該攔截器,可以自動攔截該接口,而且校驗權限。

該攔截器其實相對來講,比較簡單,能夠在DispatcherServlet類的doDispatch方法中看到調用過程:

順便說一句,這裏只講了spring mvc的攔截器,並無講spring的攔截器,是由於我有點小私心,後面就會知道。

七 Enable開關真香

不知道你有沒有用過Enable開頭的註解,好比:EnableAsync、EnableCaching、EnableAspectJAutoProxy等,這類註解就像開關同樣,只要在@Configuration定義的配置類上加上這類註解,就能開啓相關的功能。

是否是很酷?

讓咱們一塊兒實現一個本身的開關:

第一步,定義一個LogFilter:

`public class LogFilter implements Filter {`
 `@Override`
 `public void init(FilterConfig filterConfig) throws ServletException {`
 `}`
 `@Override`
 `public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {`
 `System.out.println("記錄請求日誌");`
 `chain.doFilter(request, response);`
 `System.out.println("記錄響應日誌");`
 `}`
 `@Override`
 `public void destroy() {`
 
 `}`
`}`
`複製代碼`

第二步,註冊LogFilter:

`@ConditionalOnWebApplication`
`public class LogFilterWebConfig {`
 `@Bean`
 `public LogFilter timeFilter() {`
 `return new LogFilter();`
 `}`
`}`
`複製代碼`

注意,這裏用了@ConditionalOnWebApplication註解,沒有直接使用@Configuration註解。

第三步,定義開關@EnableLog註解:

`@Target(ElementType.TYPE)`
`@Retention(RetentionPolicy.RUNTIME)`
`@Documented`
`@Import(LogFilterWebConfig.class)`
`public @interface EnableLog {`
`}`
`複製代碼`

第四步,只需在springboot啓動類加上@EnableLog註解便可開啓LogFilter記錄請求和響應日誌的功能。

八 RestTemplate攔截器的春天

咱們使用RestTemplate調用遠程接口時,有時須要在header中傳遞信息,好比:traceId,source等,便於在查詢日誌時可以串聯一次完整的請求鏈路,快速定位問題。

這種業務場景就能經過ClientHttpRequestInterceptor接口實現,具體作法以下:

第一步,實現ClientHttpRequestInterceptor接口:

`public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {`
 `@Override`
 `public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {`
 `request.getHeaders().set("traceId", MdcUtil.get());`
 `return execution.execute(request, body);`
 `}`
`}`
`複製代碼`

第二步,定義配置類:

`@Configuration`
`public class RestTemplateConfiguration {`
 `@Bean`
 `public RestTemplate restTemplate() {`
 `RestTemplate restTemplate = new RestTemplate();`
 `restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));`
 `return restTemplate;`
 `}`
 `@Bean`
 `public RestTemplateInterceptor restTemplateInterceptor() {`
 `return new RestTemplateInterceptor();`
 `}`
`}`
`複製代碼`

其中MdcUtil實際上是利用MDC工具在ThreadLocal中存儲和獲取traceId

`public class MdcUtil {`
 `private static final String TRACE_ID = "TRACE_ID";`
 `public static String get() {`
 `return MDC.get(TRACE_ID);`
 `}`
 `public static void add(String value) {`
 `MDC.put(TRACE_ID, value);`
 `}`
`}`
`複製代碼`

固然,這個例子中沒有演示MdcUtil類的add方法具體調的地方,咱們能夠在filter中執行接口方法以前,生成traceId,調用MdcUtil類的add方法添加到MDC中,而後在同一個請求的其餘地方就能經過MdcUtil類的get方法獲取到該traceId。

九 統一異常處理

之前咱們在開發接口時,若是出現異常,爲了給用戶一個更友好的提示,例如:

`@RequestMapping("/test")`
`@RestController`
`public class TestController {`
 `@GetMapping("/add")`
 `public String add() {`
 `int a = 10 / 0;`
 `return "成功";`
 `}`
`}`
`複製代碼`

若是不作任何處理請求add接口結果直接報錯:

what?用戶能直接看到錯誤信息?

這種交互方式給用戶的體驗很是差,爲了解決這個問題,咱們一般會在接口中捕獲異常:

`@GetMapping("/add")`
`public String add() {`
 `String result = "成功";`
 `try {`
 `int a = 10 / 0;`
 `} catch (Exception e) {`
 `result = "數據異常";`
 `}`
 `return result;`
`}`
`複製代碼`

接口改造後,出現異常時會提示:「數據異常」,對用戶來講更友好。

看起來挺不錯的,可是有問題。。。

若是隻是一個接口還好,可是若是項目中有成百上千個接口,都要加上異常捕獲代碼嗎?

答案是否認的,這時全局異常處理就派上用場了:RestControllerAdvice

`@RestControllerAdvice`
`public class GlobalExceptionHandler {`
 `@ExceptionHandler(Exception.class)`
 `public String handleException(Exception e) {`
 `if (e instanceof ArithmeticException) {`
 `return "數據異常";`
 `}`
 `if (e instanceof Exception) {`
 `return "服務器內部異常";`
 `}`
 `retur nnull;`
 `}`
`}`
`複製代碼`

只需在handleException方法中處理異常狀況,業務接口中能夠放心使用,再也不須要捕獲異常(有人統一處理了)。真是爽歪歪。

十 異步也能夠這麼優雅

之前咱們在使用異步功能時,一般狀況下有三種方式:

  • 繼承Thread類
  • 實現Runable接口
  • 使用線程池

讓咱們一塊兒回顧一下:

繼承Thread類

`public class MyThread extends Thread {`
 `@Override`
 `public void run() {`
 `System.out.println("===call MyThread===");`
 `}`
 `public static void main(String[] args) {`
 `new MyThread().start();`
 `}`
`}`
`複製代碼`

實現Runable接口

`public class MyWork implements Runnable {`
 `@Override`
 `public void run() {`
 `System.out.println("===call MyWork===");`
 `}`
 `public static void main(String[] args) {`
 `new Thread(new MyWork()).start();`
 `}`
`}`
`複製代碼`

使用線程池

`public class MyThreadPool {`
 `private static ExecutorService executorService = new ThreadPoolExecutor(1, 5, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200));`
 `static class Work implements Runnable {`
 `@Override`
 `public void run() {`
 `System.out.println("===call work===");`
 `}`
 `}`
 `public static void main(String[] args) {`
 `try {`
 `executorService.submit(new MyThreadPool.Work());`
 `} finally {`
 `executorService.shutdown();`
 `}`
 `}`
`}`
`複製代碼`

這三種實現異步的方法不能說很差,可是spring已經幫咱們抽取了一些公共的地方,咱們無需再繼承Thread類或實現Runable接口,它都搞定了。

如何spring異步功能呢?

第一步,springboot項目啓動類上加@EnableAsync註解。

`@EnableAsync`
`@SpringBootApplication`
`public class Application {`
 `public static void main(String[] args) {`
 `new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args);`
 `}`
`}`
`複製代碼`

第二步,在須要使用異步的方法上加上@Async註解:

`@Service`
`public class PersonService {`
 `@Async`
 `public String get() {`
 `System.out.println("===add==");`
 `return "data";`
 `}`
`}`
`複製代碼`

而後在使用的地方調用一下:personService.get();就擁有了異步功能,是否是很神奇。

默認狀況下,spring會爲咱們的異步方法建立一個線程去執行,若是該方法被調用次數很是多的話,須要建立大量的線程,會致使資源浪費。

這時,咱們能夠定義一個線程池,異步方法將會被自動提交到線程池中執行。

`@Configuration`
`public class ThreadPoolConfig {`
 `@Value("${thread.pool.corePoolSize:5}")`
 `private int corePoolSize;`
 `@Value("${thread.pool.maxPoolSize:10}")`
 `private int maxPoolSize;`
 `@Value("${thread.pool.queueCapacity:200}")`
 `private int queueCapacity;`
 `@Value("${thread.pool.keepAliveSeconds:30}")`
 `private int keepAliveSeconds;`
 `@Value("${thread.pool.threadNamePrefix:ASYNC_}")`
 `private String threadNamePrefix;`
 `@Bean`
 `public Executor MessageExecutor() {`
 `ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();`
 `executor.setCorePoolSize(corePoolSize);`
 `executor.setMaxPoolSize(maxPoolSize);`
 `executor.setQueueCapacity(queueCapacity);`
 `executor.setKeepAliveSeconds(keepAliveSeconds);`
 `executor.setThreadNamePrefix(threadNamePrefix);`
 `executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());`
 `executor.initialize();`
 `return executor;`
 `}`
`}`
`複製代碼`

spring異步的核心方法:

根據返回值不一樣,處理狀況也不太同樣,具體分爲以下狀況:

十一 據說緩存好用,沒想到這麼好用

spring cache架構圖:

它目前支持多種緩存:

咱們在這裏以caffeine爲例,它是spring官方推薦的。

第一步,引入caffeine的相關jar包

`<dependency>`
 `<groupId>org.springframework.boot</groupId>`
 `<artifactId>spring-boot-starter-cache</artifactId>`
`</dependency>`
`<dependency>`
 `<groupId>com.github.ben-manes.caffeine</groupId>`
 `<artifactId>caffeine</artifactId>`
 `<version>2.6.0</version>`
`</dependency>`
`複製代碼`

第二步,配置CacheManager,開啓EnableCaching

`@Configuration`
`@EnableCaching`
`public class CacheConfig {`
 `@Bean`
 `public CacheManager cacheManager(){`
 `CaffeineCacheManager cacheManager = new CaffeineCacheManager();`
 `//Caffeine配置`
 `Caffeine<Object, Object> caffeine = Caffeine.newBuilder()`
 `//最後一次寫入後通過固定時間過時`
 `.expireAfterWrite(10, TimeUnit.SECONDS)`
 `//緩存的最大條數`
 `.maximumSize(1000);`
 `cacheManager.setCaffeine(caffeine);`
 `return cacheManager;`
 `}`
`}`
`複製代碼`

第三步,使用Cacheable註解獲取數據

`@Service`
`public class CategoryService {`
 
 `//category是緩存名稱,#type是具體的key,可支持el表達式`
 `@Cacheable(value = "category", key = "#type")`
 `public CategoryModel getCategory(Integer type) {`
 `return getCategoryByType(type);`
 `}`
 `private CategoryModel getCategoryByType(Integer type) {`
 `System.out.println("根據不一樣的type:" + type + "獲取不一樣的分類數據");`
 `CategoryModel categoryModel = new CategoryModel();`
 `categoryModel.setId(1L);`
 `categoryModel.setParentId(0L);`
 `categoryModel.setName("電器");`
 `categoryModel.setLevel(3);`
 `return categoryModel;`
 `}`
`}`
`複製代碼`

調用categoryService.getCategory()方法時,先從caffine緩存中獲取數據,若是可以獲取到數據則直接返回該數據,不會進入方法體。若是不能獲取到數據,則直接方法體中的代碼獲取到數據,而後放到caffine緩存中。

最後說一句(求關注,別白嫖我)

若是這篇文章對您有所幫助,或者有所啓發的話,幫忙關注一下,您的支持是我堅持寫做最大的動力。

求一鍵三連:點贊、轉發、在看。
源於:juejin.cn/post/6931630572720619534

相關文章
相關標籤/搜索