Spring中這些能升華代碼的技巧,可能會讓你愛不釋手
前言
最近越來越多的讀者認可我的文章,還是件挺讓人高興的事情。有些讀者私信我說希望后面多分享spring方面的文章,這樣能夠在實際工作中派上用場。正好我對spring源碼有過一定的研究,并結合我這幾年實際的工作經(jīng)驗,把spring中我認為不錯的知識點總結一下,希望對您有所幫助。
一 如何獲取spring容器對象
1.實現(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");
- }
- }
實現(xiàn)BeanFactoryAware接口,然后重寫setBeanFactory方法,就能從該方法中獲取到spring容器對象。
2.實現(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");
- }
- }
實現(xiàn)ApplicationContextAware接口,然后重寫setApplicationContext方法,也能從該方法中獲取到spring容器對象。
3.實現(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");
- }
- }
實現(xiàn)ApplicationListener接口,需要注意的是該接口接收的泛型是ContextRefreshedEvent類,然后重寫onApplicationEvent方法,也能從該方法中獲取到spring容器對象。
此外,不得不提一下Aware接口,它其實是一個空接口,里面不包含任何方法。
它表示已感知的意思,通過這類接口可以獲取指定對象,比如:
- 通過BeanFactoryAware獲取BeanFactory
- 通過ApplicationContextAware獲取ApplicationContext
- 通過BeanNameAware獲取BeanName等
Aware接口是很常用的功能,目前包含如下功能:

二 如何初始化bean
spring中支持3種初始化bean的方法:
- xml中指定init-method方法
- 使用@PostConstruct注解
- 實現(xiàn)InitializingBean接口
第一種方法太古老了,現(xiàn)在用的人不多,具體用法就不介紹了。
1.使用@PostConstruct注解
- @Service
- public class AService {
- @PostConstruct
- public void init() {
- System.out.println("===初始化===");
- }
- }
在需要初始化的方法上增加@PostConstruct注解,這樣就有初始化的能力。
2.實現(xiàn)InitializingBean接口
- @Service
- public class BService implements InitializingBean {
- @Override
- public void afterPropertiesSet() throws Exception {
- System.out.println("===初始化===");
- }
- }
實現(xiàn)InitializingBean接口,重寫afterPropertiesSet方法,該方法中可以完成初始化功能。
這里順便拋出一個有趣的問題:init-method、PostConstruct 和 InitializingBean 的執(zhí)行順序是什么樣的?
決定他們調(diào)用順序的關鍵代碼在AbstractAutowireCapableBeanFactory類的initializeBean方法中。

這段代碼中會先調(diào)用BeanPostProcessor的postProcessBeforeInitialization方法,而PostConstruct是通過InitDestroyAnnotationBeanPostProcessor實現(xiàn)的,它就是一個BeanPostProcessor,所以PostConstruct先執(zhí)行。
而invokeInitMethods方法中的代碼:

決定了先調(diào)用InitializingBean,再調(diào)用init-method。
所以得出結論,他們的調(diào)用順序是:

三 自定義自己的Scope
我們都知道spring默認支持的Scope只有兩種:
- singleton 單例,每次從spring容器中獲取到的bean都是同一個對象。
- prototype 多例,每次從spring容器中獲取到的bean都是不同的對象。
spring web又對Scope進行了擴展,增加了:
- RequestScope 同一次請求從spring容器中獲取到的bean都是同一個對象。
- SessionScope 同一個會話從spring容器中獲取到的bean都是同一個對象。
即便如此,有些場景還是無法滿足我們的要求。
比如,我們想在同一個線程中從spring容器獲取到的bean都是同一個對象,該怎么辦?
這就需要自定義Scope了。
第一步實現(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() {
- }
- }
四 別說FactoryBean沒用
說起FactoryBean就不得不提BeanFactory,因為面試官老喜歡問它們的區(qū)別。
- BeanFactory:spring容器的頂級接口,管理bean的工廠。
- FactoryBean:并非普通的工廠bean,它隱藏了實例化一些復雜Bean的細節(jié),給上層應用帶來了便利。
如果你看過spring源碼,會發(fā)現(xiàn)它有70多個地方在用FactoryBean接口。

上面這張圖足以說明該接口的重要性,請勿忽略它好嗎?
特別提一句:mybatis的SqlSessionFactory對象就是通過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實例對象:
- @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對象。
五 輕松自定義類型轉(zhuǎn)換
spring目前支持3中類型轉(zhuǎn)換器:
- Converter
- ConverterFactory
- GenericConverter:它支持多個source和目標類型的轉(zhuǎn)化,同時還提供了source和目標類型的上下文,這個上下文能讓你實現(xiàn)基于屬性上的注解或信息來進行類型轉(zhuǎn)換。
這3種類型轉(zhuǎn)換器使用的場景不一樣,我們以Converter
第一步,定義一個實體User:
- @Data
- public class User {
- private Long id;
- private String name;
- private Date registerDate;
- }
第二步,實現(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";
- }
- }
請求接口時User對象中registerDate字段會被自動轉(zhuǎn)換成Date類型。
六 spring mvc攔截器,用過的都說好
spring mvc攔截器根spring攔截器相比,它里面能夠獲取HttpServletRequest和HttpServletResponse 等web對象實例。
spring mvc攔截器的頂層接口是:HandlerInterceptor,包含三個方法:
- preHandle 目標方法執(zhí)行前執(zhí)行
- postHandle 目標方法執(zhí)行后執(zhí)行
- afterCompletion 請求完成時執(zhí)行
為了方便我們一般情況會用HandlerInterceptor接口的實現(xiàn)類HandlerInterceptorAdapter類。
假如有權限認證、日志、統(tǒ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("===權限校驗===");
- return true;
- }
- }
第二步,將該攔截器注冊到spring容器:
- @Configuration
- public class WebAuthConfig extends WebMvcConfigurerAdapter {
- @Bean
- public AuthInterceptor getAuthInterceptor() {
- return new AuthInterceptor();
- }
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(new AuthInterceptor());
- }
- }
第三步,在請求接口時spring mvc通過該攔截器,能夠自動攔截該接口,并且校驗權限。
該攔截器其實相對來說,比較簡單,可以在DispatcherServlet類的doDispatch方法中看到調(diào)用過程:

順便說一句,這里只講了spring mvc的攔截器,并沒有講spring的攔截器,是因為我有點小私心,后面就會知道。
七 Enable開關真香
不知道你有沒有用過Enable開頭的注解,比如:EnableAsync、EnableCaching、EnableAspectJAutoProxy等,這類注解就像開關一樣,只要在@Configuration定義的配置類上加上這類注解,就能開啟相關的功能。
是不是很酷?
讓我們一起實現(xiàn)一個自己的開關:
第一步,定義一個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調(diào)用遠程接口時,有時需要在header中傳遞信息,比如:traceId,source等,便于在查詢?nèi)罩緯r能夠串聯(lián)一次完整的請求鏈路,快速定位問題。
這種業(yè)務場景就能通過ClientHttpRequestInterceptor接口實現(xiàn),具體做法如下:
第一步,實現(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其實是利用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方法具體調(diào)的地方,我們可以在filter中執(zhí)行接口方法之前,生成traceId,調(diào)用MdcUtil類的add方法添加到MDC中,然后在同一個請求的其他地方就能通過MdcUtil類的get方法獲取到該traceId。
九 統(tǒng)一異常處理
以前我們在開發(fā)接口時,如果出現(xiàn)異常,為了給用戶一個更友好的提示,例如:
- @RequestMapping("/test")
- @RestController
- public class TestController {
- @GetMapping("/add")
- public String add() {
- int a = 10 / 0;
- return "成功";
- }
- }
如果不做任何處理請求add接口結果直接報錯:

what?用戶能直接看到錯誤信息?
這種交互方式給用戶的體驗非常差,為了解決這個問題,我們通常會在接口中捕獲異常:
- @GetMapping("/add")
- lic String add() {
- String result = "成功";
- try {
- int a = 10 / 0;
- } catch (Exception e) {
- result = "數(shù)據(jù)異常";
- }
- return result;
接口改造后,出現(xiàn)異常時會提示:“數(shù)據(jù)異常”,對用戶來說更友好。
看起來挺不錯的,但是有問題。。。
如果只是一個接口還好,但是如果項目中有成百上千個接口,都要加上異常捕獲代碼嗎?
答案是否定的,這時全局異常處理就派上用場了: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 "服務器內(nèi)部異常";
- }
- retur n null;
- }
- }
只需在handleException方法中處理異常情況,業(yè)務接口中可以放心使用,不再需要捕獲異常(有人統(tǒng)一處理了)。真是爽歪歪。
十 異步也可以這么優(yōu)雅
以前我們在使用異步功能時,通常情況下有三種方式:
- 繼承Thread類
- 實現(xiàn)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();
- }
- }
實現(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();
- }
- }
使用線程池
- 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();
- }
- }
- }
這三種實現(xiàn)異步的方法不能說不好,但是spring已經(jīng)幫我們抽取了一些公共的地方,我們無需再繼承Thread類或?qū)崿F(xiàn)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";
- }
- }
然后在使用的地方調(diào)用一下:personService.get();就擁有了異步功能,是不是很神奇。
默認情況下,spring會為我們的異步方法創(chuàng)建一個線程去執(zhí)行,如果該方法被調(diào)用次數(shù)非常多的話,需要創(chuà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ù)返回值不同,處理情況也不太一樣,具體分為如下情況:

十一 聽說緩存好用,沒想到這么好用
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()
- //最后一次寫入后經(jīng)過固定時間過期
- .expireAfterWrite(10, TimeUnit.SECONDS)
- //緩存的最大條數(shù)
- .maximumSize(1000);
- cacheManager.setCaffeine(caffeine);
- return cacheManager;
- }
- }
第三步,使用Cacheable注解獲取數(shù)據(jù)
- @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("根據(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()方法時,先從caffine緩存中獲取數(shù)據(jù),如果能夠獲取到數(shù)據(jù)則直接返回該數(shù)據(jù),不會進入方法體。如果不能獲取到數(shù)據(jù),則直接方法體中的代碼獲取到數(shù)據(jù),然后放到caffine緩存中。
最后
spring中不錯的功能其實還有很多,比如:
BeanPostProcessor,BeanFactoryPostProcessor,AOP,動態(tài)數(shù)據(jù)源,ImportSelector等等。