前言
最近越来越多的读者认可我的文章,还是件挺让人快乐的事件。有些读者私信我说心愿前面多分享spring方面的文章,这样可能在理论工作中派上用场。正好我对spring源码有过肯定的钻研,并联合我这几年理论的工作教训,把spring中我认为不错的知识点总结一下,心愿对您有所帮忙。
一 如何获取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容器对象。
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容器对象。
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
接口,它其实是一个空接口,外面不蕴含任何办法。
它示意已感知的意思,通过这类接口能够获取指定对象,比方:
- 通过BeanFactoryAware获取BeanFactory
- 通过ApplicationContextAware获取ApplicationContext
- 通过BeanNameAware获取BeanName等
Aware
接口是很罕用的性能,目前蕴含如下性能:
二 如何初始化bean
spring中反对3种初始化bean的办法:
- xml中指定init-method办法
- 应用@PostConstruct注解
- 实现InitializingBean接口
第一种办法太古老了,当初用的人不多,具体用法就不介绍了。
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-method
、PostConstruct
和 InitializingBean
的执行程序是什么样的?
决定他们调用程序的要害代码在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接口。
下面这张图足以阐明该接口的重要性,请勿疏忽它好吗?
特地提一句:mybatis
的SqlSessionFactory
对象就是通过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拦截器相比,它外面可能获取HttpServletRequest
和HttpServletResponse
等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
发表回复