<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          spring中這些能升華代碼的技巧,可能會(huì)讓你愛(ài)不釋手

          共 16340字,需瀏覽 33分鐘

           ·

          2021-01-18 12:33

          前言

          最近越來(lái)越多的讀者認(rèn)可我的文章,還是件挺讓人高興的事情。有些讀者私信我說(shuō)希望后面多分享spring方面的文章,這樣能夠在實(shí)際工作中派上用場(chǎng)。正好我對(duì)spring源碼有過(guò)一定的研究,并結(jié)合我這幾年實(shí)際的工作經(jīng)驗(yàn),把spring中我認(rèn)為不錯(cuò)的知識(shí)點(diǎn)總結(jié)一下,希望對(duì)您有所幫助。

          一 如何獲取spring容器對(duì)象

          1.實(shí)現(xiàn)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");
          }
          }

          實(shí)現(xiàn)BeanFactoryAware接口,然后重寫setBeanFactory方法,就能從該方法中獲取到spring容器對(duì)象。

          2.實(shí)現(xiàn)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");
          }

          }

          實(shí)現(xiàn)ApplicationContextAware接口,然后重寫setApplicationContext方法,也能從該方法中獲取到spring容器對(duì)象。

          3.實(shí)現(xiàn)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");
          }

          }

          實(shí)現(xiàn)ApplicationListener接口,需要注意的是該接口接收的泛型是ContextRefreshedEvent類,然后重寫onApplicationEvent方法,也能從該方法中獲取到spring容器對(duì)象。

          此外,不得不提一下Aware接口,它其實(shí)是一個(gè)空接口,里面不包含任何方法。

          它表示已感知的意思,通過(guò)這類接口可以獲取指定對(duì)象,比如:

          • 通過(guò)BeanFactoryAware獲取BeanFactory
          • 通過(guò)ApplicationContextAware獲取ApplicationContext
          • 通過(guò)BeanNameAware獲取BeanName等

          Aware接口是很常用的功能,目前包含如下功能:

          二 如何初始化bean

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

          • xml中指定init-method方法
          • 使用@PostConstruct注解
          • 實(shí)現(xiàn)InitializingBean接口

          第一種方法太古老了,現(xiàn)在用的人不多,具體用法就不介紹了。

          1.使用@PostConstruct注解

          @Service
          public class AService {

          @PostConstruct
          public void init() {
          System.out.println("===初始化===");
          }
          }

          在需要初始化的方法上增加@PostConstruct注解,這樣就有初始化的能力。

          2.實(shí)現(xiàn)InitializingBean接口

          @Service
          public class BService implements InitializingBean {

          @Override
          public void afterPropertiesSet() throws Exception {
          System.out.println("===初始化===");
          }
          }

          實(shí)現(xiàn)InitializingBean接口,重寫afterPropertiesSet方法,該方法中可以完成初始化功能。

          這里順便拋出一個(gè)有趣的問(wèn)題:init-method、PostConstructInitializingBean 的執(zhí)行順序是什么樣的?

          決定他們調(diào)用順序的關(guān)鍵代碼在AbstractAutowireCapableBeanFactory類的initializeBean方法中。

          這段代碼中會(huì)先調(diào)用BeanPostProcessorpostProcessBeforeInitialization方法,而PostConstruct是通過(guò)InitDestroyAnnotationBeanPostProcessor實(shí)現(xiàn)的,它就是一個(gè)BeanPostProcessor,所以PostConstruct先執(zhí)行。

          invokeInitMethods方法中的代碼:

          決定了先調(diào)用InitializingBean,再調(diào)用init-method。

          所以得出結(jié)論,他們的調(diào)用順序是:

          三 自定義自己的Scope

          我們都知道spring默認(rèn)支持的Scope只有兩種:

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

          spring web又對(duì)Scope進(jìn)行了擴(kuò)展,增加了:

          • RequestScope 同一次請(qǐng)求從spring容器中獲取到的bean都是同一個(gè)對(duì)象。
          • SessionScope 同一個(gè)會(huì)話從spring容器中獲取到的bean都是同一個(gè)對(duì)象。

          即便如此,有些場(chǎng)景還是無(wú)法滿足我們的要求。

          比如,我們想在同一個(gè)線程中從spring容器獲取到的bean都是同一個(gè)對(duì)象,該怎么辦?

          這就需要自定義Scope了。

          第一步實(shí)現(xiàn)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() {
          }
          }

          四 別說(shuō)FactoryBean沒(méi)用

          說(shuō)起FactoryBean就不得不提BeanFactory,因?yàn)槊嬖嚬倮舷矚g問(wèn)它們的區(qū)別。

          • BeanFactory:spring容器的頂級(jí)接口,管理bean的工廠。
          • FactoryBean:并非普通的工廠bean,它隱藏了實(shí)例化一些復(fù)雜Bean的細(xì)節(jié),給上層應(yīng)用帶來(lái)了便利。

          如果你看過(guò)spring源碼,會(huì)發(fā)現(xiàn)它有70多個(gè)地方在用FactoryBean接口。

          上面這張圖足以說(shuō)明該接口的重要性,請(qǐng)勿忽略它好嗎?

          特別提一句:mybatisSqlSessionFactory對(duì)象就是通過(guò)SqlSessionFactoryBean類創(chuàng)建的。

          我們一起定義自己的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實(shí)例對(duì)象:

          @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類中g(shù)etObject方法返回的對(duì)象,

          • getBean("&myFactoryBean");獲取的才是MyFactoryBean對(duì)象。

          五 輕松自定義類型轉(zhuǎn)換

          spring目前支持3中類型轉(zhuǎn)換器:

          • Converter:將 S 類型對(duì)象轉(zhuǎn)為 T 類型對(duì)象
          • ConverterFactory:將 S 類型對(duì)象轉(zhuǎn)為 R 類型及子類對(duì)象
          • GenericConverter:它支持多個(gè)source和目標(biāo)類型的轉(zhuǎn)化,同時(shí)還提供了source和目標(biāo)類型的上下文,這個(gè)上下文能讓你實(shí)現(xiàn)基于屬性上的注解或信息來(lái)進(jìn)行類型轉(zhuǎn)換。

          這3種類型轉(zhuǎn)換器使用的場(chǎng)景不一樣,我們以Converter為例。假如:接口中接收參數(shù)的實(shí)體對(duì)象中,有個(gè)字段的類型是Date,但是實(shí)際傳參的是字符串類型:2021-01-03 10:20:15,要如何處理呢?

          第一步,定義一個(gè)實(shí)體User

          @Data
          public class User {

          private Long id;
          private String name;
          private Date registerDate;
          }

          第二步,實(shí)現(xiàn)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;
          }
          }

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

          @Configuration
          public class WebConfig extends WebMvcConfigurerAdapter {

          @Override
          public void addFormatters(FormatterRegistry registry) {
          registry.addConverter(new DateConverter());
          }
          }

          第四步,調(diào)用接口

          @RequestMapping("/user")
          @RestController
          public class UserController {

          @RequestMapping("/save")
          public String save(@RequestBody User user) {
          return "success";
          }
          }

          請(qǐng)求接口時(shí)User對(duì)象中registerDate字段會(huì)被自動(dòng)轉(zhuǎn)換成Date類型。

          六 spring mvc攔截器,用過(guò)的都說(shuō)好

          spring mvc攔截器根spring攔截器相比,它里面能夠獲取HttpServletRequestHttpServletResponse 等web對(duì)象實(shí)例。

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

          • preHandle?目標(biāo)方法執(zhí)行前執(zhí)行
          • postHandle?目標(biāo)方法執(zhí)行后執(zhí)行
          • afterCompletion?請(qǐng)求完成時(shí)執(zhí)行

          為了方便我們一般情況會(huì)用HandlerInterceptor接口的實(shí)現(xiàn)類HandlerInterceptorAdapter類。

          假如有權(quán)限認(rèn)證、日志、統(tǒng)計(jì)的場(chǎng)景,可以使用該攔截器。

          第一步,繼承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("===權(quán)限校驗(yàn)===");
          return true;
          }
          }

          第二步,將該攔截器注冊(cè)到spring容器:

          @Configuration
          public class WebAuthConfig extends WebMvcConfigurerAdapter {

          @Bean
          public AuthInterceptor getAuthInterceptor() {
          return new AuthInterceptor();
          }

          @Override
          public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(new AuthInterceptor());
          }
          }

          第三步,在請(qǐng)求接口時(shí)spring mvc通過(guò)該攔截器,能夠自動(dòng)攔截該接口,并且校驗(yàn)權(quán)限。

          該攔截器其實(shí)相對(duì)來(lái)說(shuō),比較簡(jiǎn)單,可以在DispatcherServlet類的doDispatch方法中看到調(diào)用過(guò)程:

          順便說(shuō)一句,這里只講了spring mvc的攔截器,并沒(méi)有講spring的攔截器,是因?yàn)槲矣悬c(diǎn)小私心,后面就會(huì)知道。

          七 Enable開(kāi)關(guān)真香

          不知道你有沒(méi)有用過(guò)Enable開(kāi)頭的注解,比如:EnableAsync、EnableCaching、EnableAspectJAutoProxy等,這類注解就像開(kāi)關(guān)一樣,只要在@Configuration定義的配置類上加上這類注解,就能開(kāi)啟相關(guān)的功能。

          是不是很酷?

          讓我們一起實(shí)現(xiàn)一個(gè)自己的開(kāi)關(guān):

          第一步,定義一個(gè)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("記錄請(qǐng)求日志");
          chain.doFilter(request, response);
          System.out.println("記錄響應(yīng)日志");
          }

          @Override
          public void destroy() {

          }
          }

          第二步,注冊(cè)LogFilter:

          @ConditionalOnWebApplication
          public class LogFilterWebConfig {

          @Bean
          public LogFilter timeFilter() {
          return new LogFilter();
          }
          }

          注意,這里用了@ConditionalOnWebApplication注解,沒(méi)有直接使用@Configuration注解。

          第三步,定義開(kāi)關(guān)@EnableLog注解:

          @Target(ElementType.TYPE)
          @Retention(RetentionPolicy.RUNTIME)
          @Documented
          @Import(LogFilterWebConfig.class)
          public @interface EnableLog
          {

          }

          第四步,只需在springboot啟動(dòng)類加上@EnableLog注解即可開(kāi)啟LogFilter記錄請(qǐng)求和響應(yīng)日志的功能。

          八 RestTemplate攔截器的春天

          我們使用RestTemplate調(diào)用遠(yuǎn)程接口時(shí),有時(shí)需要在header中傳遞信息,比如:traceId,source等,便于在查詢?nèi)罩緯r(shí)能夠串聯(lián)一次完整的請(qǐng)求鏈路,快速定位問(wèn)題。

          這種業(yè)務(wù)場(chǎng)景就能通過(guò)ClientHttpRequestInterceptor接口實(shí)現(xiàn),具體做法如下:

          第一步,實(shí)現(xiàn)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其實(shí)是利用MDC工具在ThreadLocal中存儲(chǔ)和獲取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);
          }
          }

          當(dāng)然,這個(gè)例子中沒(méi)有演示MdcUtil類的add方法具體調(diào)的地方,我們可以在filter中執(zhí)行接口方法之前,生成traceId,調(diào)用MdcUtil類的add方法添加到MDC中,然后在同一個(gè)請(qǐng)求的其他地方就能通過(guò)MdcUtil類的get方法獲取到該traceId。

          九 統(tǒng)一異常處理

          以前我們?cè)陂_(kāi)發(fā)接口時(shí),如果出現(xiàn)異常,為了給用戶一個(gè)更友好的提示,例如:

          @RequestMapping("/test")
          @RestController
          public class TestController {

          @GetMapping("/add")
          public String add() {
          int a = 10 / 0;
          return "成功";
          }
          }

          如果不做任何處理請(qǐng)求add接口結(jié)果直接報(bào)錯(cuò):

          what?用戶能直接看到錯(cuò)誤信息?

          這種交互方式給用戶的體驗(yàn)非常差,為了解決這個(gè)問(wèn)題,我們通常會(huì)在接口中捕獲異常:

              @GetMapping("/add")
          public String add() {
          String result = "成功";
          try {
          int a = 10 / 0;
          } catch (Exception e) {
          result = "數(shù)據(jù)異常";
          }
          return result;
          }

          接口改造后,出現(xiàn)異常時(shí)會(huì)提示:“數(shù)據(jù)異常”,對(duì)用戶來(lái)說(shuō)更友好。

          看起來(lái)挺不錯(cuò)的,但是有問(wèn)題。。。

          如果只是一個(gè)接口還好,但是如果項(xiàng)目中有成百上千個(gè)接口,都要加上異常捕獲代碼嗎?

          答案是否定的,這時(shí)全局異常處理就派上用場(chǎng)了:RestControllerAdvice

          @RestControllerAdvice
          public class GlobalExceptionHandler {

          @ExceptionHandler(Exception.class)
          public String handleException(Exception e)
          {
          if (e instanceof ArithmeticException) {
          return "數(shù)據(jù)異常";
          }
          if (e instanceof Exception) {
          return "服務(wù)器內(nèi)部異常";
          }
          retur n null;
          }
          }

          只需在handleException方法中處理異常情況,業(yè)務(wù)接口中可以放心使用,不再需要捕獲異常(有人統(tǒng)一處理了)。真是爽歪歪。

          十 異步也可以這么優(yōu)雅

          以前我們?cè)谑褂卯惒焦δ軙r(shí),通常情況下有三種方式:

          • 繼承Thread類
          • 實(shí)現(xiàn)Runable接口
          • 使用線程池

          讓我們一起回顧一下:

          1. 繼承Thread類
          public  class MyThread extends Thread {

          @Override
          public void run() {
          System.out.println("===call MyThread===");
          }

          public static void main(String[] args) {
          new MyThread().start();
          }
          }
          1. 實(shí)現(xiàn)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();
          }
          }
          1. 使用線程池
          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();
          }

          }
          }

          這三種實(shí)現(xiàn)異步的方法不能說(shuō)不好,但是spring已經(jīng)幫我們抽取了一些公共的地方,我們無(wú)需再繼承Thread類或?qū)崿F(xiàn)Runable接口,它都搞定了。

          如何spring異步功能呢?

          第一步,springboot項(xiàng)目啟動(dòng)類上加@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";
          }
          }

          然后在使用的地方調(diào)用一下:personService.get();就擁有了異步功能,是不是很神奇。

          默認(rèn)情況下,spring會(huì)為我們的異步方法創(chuàng)建一個(gè)線程去執(zhí)行,如果該方法被調(diào)用次數(shù)非常多的話,需要?jiǎng)?chuàng)建大量的線程,會(huì)導(dǎo)致資源浪費(fèi)。

          這時(shí),我們可以定義一個(gè)線程池,異步方法將會(huì)被自動(dòng)提交到線程池中執(zhí)行。

          @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異步的核心方法:

          根據(jù)返回值不同,處理情況也不太一樣,具體分為如下情況:

          十一 聽(tīng)說(shuō)緩存好用,沒(méi)想到這么好用

          spring cache架構(gòu)圖:

          它目前支持多種緩存:

          我們?cè)谶@里以caffeine為例,它是spring官方推薦的。

          第一步,引入caffeine的相關(guān)jar包


          org.springframework.boot
          spring-boot-starter-cache


          com.github.ben-manes.caffeine
          caffeine
          2.6.0

          第二步,配置CacheManager,開(kāi)啟EnableCaching


          @Configuration
          @EnableCaching
          public class CacheConfig {
          @Bean
          public CacheManager cacheManager(){
          CaffeineCacheManager cacheManager = new CaffeineCacheManager();
          //Caffeine配置
          Caffeine caffeine = Caffeine.newBuilder()
          //最后一次寫入后經(jīng)過(guò)固定時(shí)間過(guò)期
          .expireAfterWrite(10, TimeUnit.SECONDS)
          //緩存的最大條數(shù)
          .maximumSize(1000);
          cacheManager.setCaffeine(caffeine);
          return cacheManager;
          }
          }

          第三步,使用Cacheable注解獲取數(shù)據(jù)

          @Service
          public class CategoryService {

          //category是緩存名稱,#type是具體的key,可支持el表達(dá)式
          @Cacheable(value = "category", key = "#type")
          public CategoryModel getCategory(Integer type) {
          return getCategoryByType(type);
          }

          private CategoryModel getCategoryByType(Integer type) {
          System.out.println("根據(jù)不同的type:" + type + "獲取不同的分類數(shù)據(jù)");
          CategoryModel categoryModel = new CategoryModel();
          categoryModel.setId(1L);
          categoryModel.setParentId(0L);
          categoryModel.setName("電器");
          categoryModel.setLevel(3);
          return categoryModel;
          }
          }

          調(diào)用categoryService.getCategory()方法時(shí),先從caffine緩存中獲取數(shù)據(jù),如果能夠獲取到數(shù)據(jù)則直接返回該數(shù)據(jù),不會(huì)進(jìn)入方法體。如果不能獲取到數(shù)據(jù),則直接方法體中的代碼獲取到數(shù)據(jù),然后放到caffine緩存中。

          嘮嘮家常

          spring中不錯(cuò)的功能其實(shí)還有很多,比如:BeanPostProcessor,BeanFactoryPostProcessor,AOP,動(dòng)態(tài)數(shù)據(jù)源,ImportSelector等等。我原本打算一篇文章寫全的,但是有兩件事情改變了我的注意:

          1. 有個(gè)大佬原本打算轉(zhuǎn)載我文章的,卻因?yàn)槠L(zhǎng)一直沒(méi)有保存成功。
          2. 最近經(jīng)常加班,真的沒(méi)多少時(shí)間寫文章,晚上還要帶娃,喂奶,換尿布,其實(shí)挺累的。

          如果大家喜歡這類文章的話,我打算把spring這些有用的知識(shí)點(diǎn)拆分一下,寫成一個(gè)系列,敬請(qǐng)期待。

          —?【 THE END 】—
          本公眾號(hào)全部博文已整理成一個(gè)目錄,請(qǐng)?jiān)诠娞?hào)里回復(fù)「m」獲?。?/span>


          3T技術(shù)資源大放送!包括但不限于:Java、C/C++,Linux,Python,大數(shù)據(jù),人工智能等等。在公眾號(hào)內(nèi)回復(fù)「1024」,即可免費(fèi)獲取?。?/span>




          瀏覽 13
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲高清在线观看视频 | 中日韩无码视频 | 日本黄色影院在线 | 免费A片网址 | 操爱 |