平时应用SpringBoot开发我的项目,少不了要应用到它的注解。这些注解让咱们解脱了繁琐的传统Spring XML配置,让咱们开发我的项目更加高效,明天咱们就来聊聊SpringBoot中罕用的注解!

SpringBoot实战电商我的项目mall(50k+star)地址:https://github.com/macrozheng/mall

罕用注解概览

这里整顿了一张SpringBoot罕用注解的思维导图,本文次要解说这些注解的用法。

组件相干注解

@Controller

用于润饰MVC中controller层的组件,SpringBoot中的组件扫描性能会辨认到该注解,并为润饰的类实例化对象,通常与@RequestMapping联用,当SpringMVC获取到申请时会转发到指定门路的办法进行解决。

/** * @auther macrozheng * @description 后盾用户治理Controller * @date 2018/4/26 * @github https://github.com/macrozheng */@Controller@RequestMapping("/admin")public class UmsAdminController {    }

@Service

用于润饰service层的组件,service层组件专一于零碎业务逻辑的解决,同样会被组件扫描并生成实例化对象。

/** * @auther macrozheng * @description 后盾用户治理Service实现类 * @date 2018/4/26 * @github https://github.com/macrozheng */@Servicepublic class UmsAdminServiceImpl implements UmsAdminService {    }

@Repository

用于润饰dao层的组件,dao层组件专一于零碎数据的解决,例如数据库中的数据,同样会被组件扫描并生成实例化对象。

/** * @auther macrozheng * @description 后盾用户与角色关系治理自定义Dao * @date 2018/10/8 * @github https://github.com/macrozheng */@Repositorypublic interface UmsAdminRoleRelationDao {    }

@Component

用于润饰SpringBoot中的组件,会被组件扫描并生成实例化对象。@Controller@Service@Repository都是非凡的组件注解。

/** * @auther macrozheng * @description 勾销订单音讯的生产者组件 * @date 2018/9/14 * @github https://github.com/macrozheng */@Componentpublic class CancelOrderSender {    }

依赖注入注解

@Autowired

会依据对象的类型主动注入依赖对象,默认要求注入对象实例必须存在,能够配置required=false来注入不肯定存在的对象。

/** * @auther macrozheng * @description 后盾用户治理Controller * @date 2018/4/26 * @github https://github.com/macrozheng */@Controller@RequestMapping("/admin")public class UmsAdminController {    @Autowired    private UmsAdminService adminService;}

@Resource

默认会依据对象的名称主动注入依赖对象,如果想要依据类型进行注入,能够设置属性为type = UmsAdminService.class

/** * @auther macrozheng * @description 后盾用户治理Controller * @date 2018/4/26 * @github https://github.com/macrozheng */@Controller@RequestMapping("/admin")public class UmsAdminController {    @Autowired    @Resource(name = "umsAdminServiceImpl")    private UmsAdminService adminService;}

@Qualifier

当同一个对象有多个实例能够注入时,应用@Autowired注解无奈进行注入,这时能够应用@Qualifier注解指定实例的名称进行准确注入。

/** * @auther macrozheng * @description 后盾用户治理Controller * @date 2018/4/26 * @github https://github.com/macrozheng */@Controller@RequestMapping("/admin")public class UmsAdminController {    @Autowired    @Qualifier("umsAdminServiceImpl")    private UmsAdminService adminService;}

实例与生命周期相干注解

@Bean

用于润饰办法,标识该办法会创立一个Bean实例,并交给Spring容器来治理。

/** * @auther macrozheng * @description RestTemplate相干配置 * @date 2018/4/26 * @github https://github.com/macrozheng */@Configurationpublic class RestTemplateConfig {    @Bean    public RestTemplate restTemplate(){        return new RestTemplate();    }}

@Scope

用于申明一个SpringBean实例的作用域,作用域的范畴有以下几种:

  • singleton:单例模式,在Spring容器中该实例惟一,Spring默认的实例模式。
  • prototype:原型模式,每次应用实例都将从新创立。
  • request:在同一申请中应用雷同的实例,不同申请从新创立。
  • session:在同一会话中应用雷同的实例,不同会话从新创立。
/** * @auther macrozheng * @description RestTemplate相干配置 * @date 2018/4/26 * @github https://github.com/macrozheng */@Configurationpublic class RestTemplateConfig {    @Bean    @Scope("singleton")    public RestTemplate restTemplate(){        return new RestTemplate();    }}

@Primary

当同一个对象有多个实例时,优先选择该实例。

/** * @auther macrozheng * @description Jackson相干配置,配置json不返回null的字段 * @date 2018/8/2 * @github https://github.com/macrozheng */@Configurationpublic class JacksonConfig {    @Bean    @Primary    @ConditionalOnMissingBean(ObjectMapper.class)    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {        ObjectMapper objectMapper = builder.createXmlMapper(false).build();        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);        return objectMapper;    }}

@PostConstruct

用于润饰办法,当对象实例被创立并且依赖注入实现后执行,可用于对象实例的初始化操作。

@PreDestroy

用于润饰办法,当对象实例将被Spring容器移除时执行,可用于对象实例持有资源的开释。

@PostConstruct、@PreDestroy示例

/** * @auther macrozheng * @description 动静权限数据源,用于获取动静权限规定 * @date 2020/2/7 * @github https://github.com/macrozheng */public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {    private static Map<String, ConfigAttribute> configAttributeMap = null;    @Autowired    private DynamicSecurityService dynamicSecurityService;    @PostConstruct    public void loadDataSource() {        configAttributeMap = dynamicSecurityService.loadDataSource();    }    @PostConstruct    public void loadDataSource() {        configAttributeMap = dynamicSecurityService.loadDataSource();    }    @PreDestroy    public void clearDataSource() {        configAttributeMap.clear();        configAttributeMap = null;    }}

SpringMVC相干注解

@RequestMapping

可用于将Web申请门路映射到解决类的办法上,当作用于类上时,能够对立类中所有办法的路由门路,当作用于办法上时,可独自指定办法的路由门路。

method属性能够指定申请的形式,如GET、POST、PUT、DELETE等。

@RequestBody

示意办法的申请参数为JSON格局,从Body中传入,将主动绑定到办法参数对象中。

@ResponseBody

示意办法将返回JSON格局的数据,会主动将返回的对象转化为JSON数据。

@RequestParam

用于接管申请参数,能够是如下三种模式:

  • query param:GET申请拼接在地址里的参数。
  • form data:POST表单提交的参数。
  • multipart:文件上传申请的局部参数。

@PathVariable

用于接管申请门路中的参数,罕用于REST格调的API。

@RequestPart

用于接管文件上传中的文件参数,通常是multipart/form-data模式传入的参数。

/** * @auther macrozheng * @description MinIO对象存储管理Controller * @date 2019/12/25 * @github https://github.com/macrozheng */@Controller@RequestMapping("/minio")public class MinioController {    @RequestMapping(value = "/upload", method = RequestMethod.POST)    @ResponseBody    public CommonResult upload(@RequestPart("file") MultipartFile file) {            //省略文件上传操作...            return CommonResult.success(minioUploadDto);    }}

SpringMVC注解示例

/** * @auther macrozheng * @description 后盾用户治理Controller * @date 2018/4/26 * @github https://github.com/macrozheng */@Controller@RequestMapping("/admin")public class UmsAdminController {    @RequestMapping(value = "/register", method = RequestMethod.POST)    @ResponseBody    public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam) {        UmsAdmin umsAdmin = adminService.register(umsAdminParam);        if (umsAdmin == null) {            return CommonResult.failed();        }        return CommonResult.success(umsAdmin);    }        @RequestMapping(value = "/list", method = RequestMethod.GET)    @ResponseBody    public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {        List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);        return CommonResult.success(CommonPage.restPage(adminList));    }    @RequestMapping(value = "/{id}", method = RequestMethod.GET)    @ResponseBody    public CommonResult<UmsAdmin> getItem(@PathVariable Long id) {        UmsAdmin admin = adminService.getItem(id);        return CommonResult.success(admin);    }}

@RestController

用于示意controller层的组件,与@Controller注解的不同在于,相当于在每个申请解决办法上都增加了@ResponseBody注解,这些办法都将返回JSON格局数据。

@GetMapping

用于示意GET申请办法,等价于@RequestMapping(method = RequestMethod.GET)

@PostMapping

用于示意POST申请办法,等价于@RequestMapping(method = RequestMethod.POST)

REST格调注解示例

/** * @auther macrozheng * @description 后盾用户治理Controller * @date 2018/4/26 * @github https://github.com/macrozheng */@RestController@RequestMapping("/admin")public class UmsAdminController {    @PostMapping("/register")    public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam) {        UmsAdmin umsAdmin = adminService.register(umsAdminParam);        if (umsAdmin == null) {            return CommonResult.failed();        }        return CommonResult.success(umsAdmin);    }    @GetMapping("/list")    public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {        List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);        return CommonResult.success(CommonPage.restPage(adminList));    }}

配置相干注解

@Configuration

用于申明一个Java模式的配置类,SpringBoot举荐应用Java配置,在该类中申明的Bean等配置将被SpringBoot的组件扫描性能扫描到。

/** * @auther macrozheng * @description MyBatis相干配置 * @date 2019/4/8 * @github https://github.com/macrozheng */@Configuration@MapperScan({"com.macro.mall.mapper","com.macro.mall.dao"})public class MyBatisConfig {}

@EnableAutoConfiguration

启用SpringBoot的自动化配置,会依据你在pom.xml增加的依赖和application-dev.yml中的配置主动创立你须要的配置。

@Configuration@EnableAutoConfigurationpublic class AppConfig {}

@ComponentScan

启用SpringBoot的组件扫描性能,将主动拆卸和注入指定包下的Bean实例。

@Configuration@ComponentScan({"xyz.erupt","com.macro.mall.tiny"})public class EruptConfig {}

@SpringBootApplication

用于示意SpringBoot利用中的启动类,相当于@EnableAutoConfiguration@EnableAutoConfiguration@ComponentScan三个注解的结合体。

@SpringBootApplicationpublic class MallTinyApplication {    public static void main(String[] args) {        SpringApplication.run(MallTinyApplication.class, args);    }}

@EnableCaching

当增加Spring Data Redis依赖之后,可用该注解开启Spring基于注解的缓存治理性能。

/** * @auther macrozheng * @description Redis配置类 * @date 2020/3/2 * @github https://github.com/macrozheng */@EnableCaching@Configurationpublic class RedisConfig extends BaseRedisConfig {}

@value

用于注入在配置文件中配置好的属性,例如咱们能够在application.yml配置如下属性:

jwt:  tokenHeader: Authorization #JWT存储的申请头  secret: mall-admin-secret #JWT加解密应用的密钥  expiration: 604800 #JWT的超期限工夫(60*60*24*7)  tokenHead: 'Bearer '  #JWT负载中拿到结尾

而后在Java类中就能够应用@Value注入并进行应用了。

public class JwtTokenUtil {    @Value("${jwt.secret}")    private String secret;    @Value("${jwt.expiration}")    private Long expiration;    @Value("${jwt.tokenHead}")    private String tokenHead;}

@ConfigurationProperties

用于批量注入内部配置,以对象的模式来导入指定前缀的配置,比方这里咱们在application.yml中指定了secure.ignored为前缀的属性:

secure:  ignored:    urls: #平安门路白名单      - /swagger-ui/      - /swagger-resources/**      - /**/v2/api-docs      - /**/*.html      - /**/*.js      - /**/*.css      - /**/*.png      - /**/*.map      - /favicon.ico      - /actuator/**      - /druid/**

而后在Java类中定义一个urls属性就能够导入配置文件中的属性了。

/** * @auther macrozheng * @description SpringSecurity白名单资源门路配置 * @date 2018/11/5 * @github https://github.com/macrozheng */@Getter@Setter@Configuration@ConfigurationProperties(prefix = "secure.ignored")public class IgnoreUrlsConfig {    private List<String> urls = new ArrayList<>();}

@Conditional

用于示意当某个条件满足时,该组件或Bean将被Spring容器创立,上面是几个罕用的条件注解。

  • @ConditionalOnBean:当某个Bean存在时,配置失效。
  • @ConditionalOnMissingBean:当某个Bean不存在时,配置失效。
  • @ConditionalOnClass:当某个类在Classpath存在时,配置失效。
  • @ConditionalOnMissingClass:当某个类在Classpath不存在时,配置失效。
/** * @auther macrozheng * @description Jackson相干配置,配置json不返回null的字段 * @date 2018/8/2 * @github https://github.com/macrozheng */@Configurationpublic class JacksonConfig {    @Bean    @Primary    @ConditionalOnMissingBean(ObjectMapper.class)    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {        ObjectMapper objectMapper = builder.createXmlMapper(false).build();        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);        return objectMapper;    }}

数据库事务相干注解

@EnableTransactionManagement

启用Spring基于注解的事务管理性能,须要和@Configuration注解一起应用。

/** * @auther macrozheng * @description MyBatis相干配置 * @date 2019/4/8 * @github https://github.com/macrozheng */@Configuration@EnableTransactionManagement@MapperScan({"com.macro.mall.mapper","com.macro.mall.dao"})public class MyBatisConfig {}

@Transactional

示意办法和类须要开启事务,当作用与类上时,类中所有办法均会开启事务,当作用于办法上时,办法开启事务,办法上的注解无奈被子类所继承。

/** * @auther macrozheng * @description 前台订单治理Service * @date 2018/8/30 * @github https://github.com/macrozheng */public interface OmsPortalOrderService {    /**     * 依据提交信息生成订单     */    @Transactional    Map<String, Object> generateOrder(OrderParam orderParam);}

SpringSecurity相干注解

@EnableWebSecurity

启用SpringSecurity的Web性能。

@EnableGlobalMethodSecurity

启用SpringSecurity基于办法的平安性能,当咱们应用@PreAuthorize润饰接口办法时,须要有对应权限的用户能力拜访。

SpringSecurity配置示例

/** * @auther macrozheng * @description SpringSecurity配置 * @date 2019/10/8 * @github https://github.com/macrozheng */@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfig{    }

全局异样解决注解

@ControllerAdvice

常与@ExceptionHandler注解一起应用,用于捕捉全局异样,能作用于所有controller中。

@ExceptionHandler

润饰办法时,示意该办法为解决全局异样的办法。

全局异样解决示例

/** * @auther macrozheng * @description 全局异样解决 * @date 2020/2/27 * @github https://github.com/macrozheng */@ControllerAdvicepublic class GlobalExceptionHandler {    @ResponseBody    @ExceptionHandler(value = ApiException.class)    public CommonResult handle(ApiException e) {        if (e.getErrorCode() != null) {            return CommonResult.failed(e.getErrorCode());        }        return CommonResult.failed(e.getMessage());    }}

AOP相干注解

@Aspect

用于定义切面,切面是告诉和切点的联合,定义了何时、何地利用告诉性能。

@Before

示意前置告诉(Before),告诉办法会在指标办法调用之前执行,告诉形容了切面要实现的工作以及何时执行。

@After

示意后置告诉(After),告诉办法会在指标办法返回或抛出异样后执行。

@AfterReturning

示意返回告诉(AfterReturning),告诉办法会在指标办法返回后执行。

@AfterThrowing

示意异样告诉(AfterThrowing),告诉办法会在指标办法返回后执行。

@Around

示意盘绕告诉(Around),告诉办法会将指标办法封装起来,在指标办法调用之前和之后执行自定义的行为。

@Pointcut

定义切点表达式,定义了告诉性能被利用的范畴。

@Order

用于定义组件的执行程序,在AOP中指的是切面的执行程序,value属性越低优先级越高。

AOP相干示例

/** * @auther macrozheng * @description 对立日志解决切面 * @date 2018/4/26 * @github https://github.com/macrozheng */@Aspect@Component@Order(1)public class WebLogAspect {    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);    @Pointcut("execution(public * com.macro.mall.tiny.controller.*.*(..))")    public void webLog() {    }    @Before("webLog()")    public void doBefore(JoinPoint joinPoint) throws Throwable {    }    @AfterReturning(value = "webLog()", returning = "ret")    public void doAfterReturning(Object ret) throws Throwable {    }    @Around("webLog()")    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {        WebLog webLog = new WebLog();        //省略日志解决操作...        Object result = joinPoint.proceed();        LOGGER.info("{}", JSONUtil.parse(webLog));        return result;    }    }

测试相干注解

@SpringBootTest

用于指定测试类启用Spring Boot Test性能,默认会提供Mock环境。

@Test

指定办法为测试方法。

测试示例

/** * @auther macrozheng * @description JUnit根本测试 * @date 2022/10/11 * @github https://github.com/macrozheng */@SpringBootTestpublic class FirstTest {    @Test    public void test() {        int a=1;        Assertions.assertEquals(1,a);    }}

总结

这些SpringBoot注解根本都是我平时做我的项目罕用的注解,在我的电商实战我的项目mall中根本都用到了,这里做了一番整顿演绎,心愿对大家有所帮忙!