本文共 17469 字,大约阅读时间需要 58 分钟。
@SpringBootApplication
组合注解,用在启动类上,源码:
@Retention(RetentionPolicy.RUNTIME)@SpringBootConfiguration@EnableAutoConfiguration@ComponentScanpublic @interface SpringBootApplication
========================
@SpringBootConfiguration
@Configurationpublic @interface SpringBootConfiguration
SpringBootConfiguration标注这个类是一个配置类,是@Configuration注解的派生注解,和@Configuration注解的功能一致,标注这个类是一个配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。
只不过@SpringBootConfiguration是springboot的注解,而@Configuration是spring的注解,关于@Configuration注解,更详细的,可以参看《》--------------------------------------------
@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)的时候,才启用自动配置Spring中也有一种类似与的加载机制。它在META-INF/spring.factories文件中配置接口的实现类名称,然后在程序中读取这些配置文件并实例化。这种自定义的SPI机制是Spring Boot Starter实现的基础。
从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配置文件,并读取配置--------------------------------------------
@Configuration
@Componentpublic @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。
当使用Configuration注解时,生成当前对象的子类Class,并对方法拦截,第二次调用方法时直接从BeanFactory之中获取对象,所以得到的是同一个对象。
在Spring提供的@Configuration配置类中,就有这种场景的应用,可以看到c1和c2是同一个对象引用,而不是每次调用方法都new一个新的对象。
-------------------------------------------
@Bean
@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。
@Component 和 @Bean 的区别
@Component(和@Service和@Repository)用于自动检测和使用类路径扫描自动配置bean。注释类和bean之间存在隐式的一对一映射(即每个类一个bean)。
这种方法对需要进行逻辑处理的控制非常有限,因为它纯粹是声明性的。@Bean用于显式声明单个bean,而不是让Spring像上面那样自动执行它。它将bean的声明与类定义分离,并允许您精确地创建和配置bean。
而@Bean则常和@Configuration注解搭配使用。
如果想将第三方的类变成组件,你又没有没有源代码,也就没办法使用@Component进行自动配置,这种时候使用@Bean就比较合适了。
Spring中的@Bean是否一定要与@Configuration一起用?
使用@Configuration注解,此时调用方法返回的是被Spring管理的单例Bean。
如果换做是@Component 注解,那么调用了方法返回的对象是执行这个方法返回的对象实例,而不是被spring管理的对象。 这就是差别所在。
作用对象不同: @Component 注解作用于类,而 @Bean 注解作用于方法;
@Component 通常是通过类路径扫描来自动侦测,以及自动装配到 Spring 容器中(可以使用 @ComponentScan注解定义要扫描的路径,从中找出标识了需要装配的类,并自动装配到 Spring 的 bean 容器中)。@Bean 注解通常是在标有该注解的方法中定义产生这个 bean,@Bean告诉了 Spring 这是某个类的示例,当需要用到它的时候还给我;
@Bean 注解比 Component 注解的更灵活,而且很多地方我们只能通过 @Bean 注解来注册 bean。比如当我们引用第三方库中的类需要装配到 Spring容器时,则只能通过 @Bean来实现。----------------------------------------
@Scope
@Scope默认是单例模式,即scope="singleton"。
另外scope还有prototype、request、session、global session作用域。scope="prototype"多例
@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 @Bean public 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
即可。
----------------------------------------
@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 方法
未用@componscan注解指定扫描的包时,默认扫描的是@import注解所在的包。
可以再次添加一个配置文件,在配置文件指定我们需要扫描的包,在代码中加入逻辑:若@component不存在或未指定,则使用配置文件中指定的路径进行扫描。
给容器中注册组件; 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。
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;@RestControllerpublic class TestController { @Autowired private ImportDemo importDemo; @RequestMapping("/") public String sayHello() { return importDemo.doSomething(); }}
---------------------------------------
@ConditionalOnClass和ConditionalOnMissingBean
@ConditionalOnClass是Springboot实现自动配置的重要支撑之一。其用途是判断当前classpath下是否存在指定类,若是则将当前的配置装载入spring容器。
@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
=======================
@Value
三种方式
//使用@Value赋值; //1、基本数值 //2、可以写SpEL; #{} //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值) @Value("TomCat") private String name; @Value("#{12-2}") private Integer age; @Value("${person.tomName}") private String tomName;
@Value一个一个注入,单个配置项
-------------------------------------
@ConfigurationProperties
想把配置文件的信息,读取并自动封装成实体类,批量注入配置文件中的属性,多个配置项用一个配置类。
--------------------------------------------
@Qualifier
在Controller中需要注入service那么我的这个server有两个实现类如何区分开这两个impl呢? Qualifier的意思是合格者,通过这个标示,表明了哪个实现类才是我们所需要的,添加@Qualifier注解,需要注意的是@Qualifier的参数名称为我们之前定义@Service注解的名称之一。 使用@resource注入时比较简单了注解自带了“name”的val就是@Service注解的名称之一。 https://blog.csdn.net/qq_36567005/article/details/80611139Qualifier多数据源实现:
------------------------------------
@PropertySource
加载指定配置文件。
如果应用比较大的时候,如果所有的内容都当在一个文件中,如“application.properties”或者“application.yml”中时,就会显得比较臃肿,同时也不太好理解和维护
可以将一个文件拆分为多个,此时使用@PropertySource即可解决问题。
---------------------
@importSource
通过@importSource来加载.xml文件将配置加载到spring环境中
----------------------------
@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,那么就读不到了
---------------
@RestController
是Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。而@Controller是用来创建处理http请求的对象,一般结合@RequestMapping使用。
----------------------
@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
------------------
@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
@PostConstruct和 @PreDestroy注解位于 java.xml.ws.annotation包是Java EE的模块的一部分。J2EE已经在Java 9中被弃用,并且计划在Java 11中删除它
为pom.xml或build.gradle添加必要的依赖项
(Java 9+中的Spring @PostConstruct和@PreDestroy替代品)=========================
SpringBoot利用@WebFilter配置Filter
@WebFilter 用于将一个类声明为过滤器,该注解将会在部署时被容器处理,容器将根据具体的属性配置将相应的类部署为过滤器。该注解具有下表给出的一些常用属性 ( 以下所有属性均为可选属性,但是 value、urlPatterns、servletNames 三者必需至少包含一个,且 value 和 urlPatterns 不能共存,如果同时指定,通常忽略 value 的取值 )
@WebFilter(filterName = "FilterDemo01", urlPatterns = { "/*" })public class FilterDemo01 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("----FilterDemo01过滤器初始化----"); } @Override public 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); } @Override public void destroy() { System.out.println("----过滤器销毁----"); }}
使用@ControllerAdvice和@ExceptionHandler注解
在SpringBoot应用中使用统一异常处理
@ControllerAdvice
这是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:
全局异常处理
使用 @ControllerAdvice 实现全局异常处理,只需要定义类,添加该注解即可定义
@ExceptionHandler 注解用来指明异常的处理类型
全局数据绑定
全局数据绑定功能可以用来做一些初始化的数据操作,我们可以将一些公共的数据定义在添加了 @ControllerAdvice 注解的类中,这样,在每一个 Controller 的接口中,就都能够访问导致这些数据。
使用 @ModelAttribute 注解标记该方法的返回数据是一个全局数据
全局数据预处理
两个实体类都有一个 name 属性,从前端传递时 ,无法区分。此时,通过 @ControllerAdvice 的全局数据预处理可以解决这个问题
@Slf4j@ControllerAdvicepublic 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
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@RestControllerAdvicepublic 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); }}
转载地址:https://linuxstyle.blog.csdn.net/article/details/104042826 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!