Java 小记 — Spring Boot 注解
前言
本篇随笔将对 Spring Boot 中的常用注解做一个简单的整理归档,写作顺序将从启动类开始并逐步向内外扩展,目的即为了分享也为了方便自己日后的回顾与查阅。

1. Application
启动类示例如下:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第一个要讲解的注解是:@SpringBootApplication,从直观的感受来看,他是 SpringApplication 能够进入一系列复杂启动流程的先决条件。进入源码我们可以观察到这是一个组合注解,其切面之上还有三个注解,分别为:@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。
@SpringBootConfiguration 中真正起作用的是 @Configuration,即标注当前类为 JavaConfig 配置类(这里扩展一下,任何标注了 @Configuration 的类都为配置类,任何标注了 @Bean 的方法其返回值都是一个 Bean 的定义)。
@EnableAutoConfiguration 是构成上诉组合注解的核心,从名称上就能获取到浅显的信息:启用自动配置,他借助 @Import 将所有符合条件的 @Configuration 配置都注入到 IoC 容器中,定义如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
@ComponentScan 顾名思义,他会扫描带有特定标注的组件(如 @Controller、@Component、@Service、@Repository),并将其注入到 IoC 容器中。
2. Test
测试类示例如下:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Test
public void contextLoads() {
}
}
@RunWith(SpringRunner.class) 翻译一下就是使用 Spring 的 IoC 容器运行测试;@SpringBootTest 创建了 SpringApplication 的上下文;@Test 标注测试方法。在此推荐阅读 “SpringBoot单元测试” ,写得很详细,我就不再赘述了,待有空补几篇复杂测试的案例分析。
3. 基本注解
3.1 @Service & @Repository
他们是在 Spring Boot 中轻松实现面向接口编程的关键,一个用于逻辑层,一个用于数据层,示例如下:
public interface HelloService {
String notSay();
}
@Service
public class HelloServiceImpl implements HelloService {
@Override
public String notSay() {
return "shut up";
}
}
个人认为此处非常形象地体现了 “约定优于配置”,可以理解为 Spring Boot 默认配置了这么一条 Bean:
<bean id="HelloService" class="com.youclk.annotation.service.impl.HelloServiceImpl"></bean>
3.2 @Component
标注组件,可以作用在任何层次。
3.3 @Controller
控制器示例如下:
@RestController
public class HelloController {
private final HelloService helloService;
@Autowired
public HelloController(HelloService helloService) {
this.helloService = helloService;
}
@GetMapping("/{id}")
public String say(@PathVariable("id") Integer id, @RequestParam("name") String name) {
return (String.format("id=%d,name=%s;please %s", id, name, helloService.notSay()));
}
}
@RestController 查看源码可观察出其为 @Controller + @ResponseBody 的组合注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(annotation = Controller.class)
String value() default "";
}
@GetMapping 其实就是对 @RequestMapping(method = RequestMethod.GET) 的进一步封装,同理的还有 Post、Delete、Put 等等,不同类型的请求都有其对应封装,能少打不少代码。
其他的在示例中也一目了然了:@Autowired 自动转配;@PathVariable 从 Url 中取值;@RequestParam 从参数中取值。
4. 异常处理
示例如下:
@ControllerAdvice
public class GlobalException {
@ResponseBody
@ExceptionHandler
public String processException(Exception e) {
return "error: " + e.getMessage();
}
}
没啥好说的,@ExceptionHandler 可以过滤具体的异常类型:@ExceptionHandler(Exception.class)
5. 配置
通过 @Value 可以直接拿到配置文件中的属性,不过意义不是很大,例:
@Value("${my.name}")
private String name;
更多的时候应该去拿到一个对象,例:
@Component
@ConfigurationProperties(prefix = "my")
public class My {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
@Profiles 按环境变量激活,我觉得很不是很好的解决方案,没怎么用过,示例:
@profile("dev")
@profile("prod")
Spring Boot 提倡约定优于配置,但有的时候我们不想守约,如下:
@Configuration
public class DbConfiguration {
private final Db db;
@Autowired
public DbConfiguration(Db db) {
this.db = db;
}
@Bean(name = "dataSource")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(db.driverClassName);
dataSource.setUrl(db.driverUrl);
dataSource.setUsername(db.driverUsername);
dataSource.setPassword(db.driverPassword);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
6. 其他
@Qualifier 是为了解决一个接口对应多个实现的冲突,不过在设计上一般都会避免这种情况,所以不是很常用,示例:
@Service("service1")
public class HelloServiceImpl1 implements HelloService {
}
@Service("service2")
public class HelloServiceImpl2 implements HelloService {
}
@Autowired
@Qualifier("service1")
HelloService helloService;
@Resource(name="name",type="type") 和 @Autowired 类似,不常用。
结语
近期正在寻觅新的工作机会,若有意向,欢迎留言,微信: youclk。
我的公众号《有刻》,我们共同成长!

Java 小记 — Spring Boot 注解的更多相关文章
- Java 小记 — Spring Boot 的实践与思考
前言 本篇随笔用于记录我在学习 Java 和构建 Spring Boot 项目过程中的一些思考,包含架构.组件和部署方式等.下文仅为概要,待闲时逐一整理为详细文档. 1. 组件 开源社区如火如荼,若在 ...
- Spring boot 注解简单备忘
Spring boot 注解简单备忘 1.定义注解 package com.space.aspect.anno;import java.lang.annotation.*; /** * 定义系统日志注 ...
- Spring Boot 注解之ObjectProvider源码追踪
最近依旧在学习阅读Spring Boot的源代码,在此过程中涉及到很多在日常项目中比较少见的功能特性,对此深入研究一下,也挺有意思,这也是阅读源码的魅力之一.这里写成文章,分享给大家. 自动配置中的O ...
- Spring Boot注解大全,一键收藏了!
本文首发于微信公众号[猿灯塔],转载引用请说明出处 今天是猿灯塔“365天原创计划”第5天. 今天呢!灯塔君跟大家讲: Spring Boot注解大全 一.注解(annotations)列表 @Spr ...
- Spring boot注解(annotation)含义详解
Spring boot注解(annotation)含义详解 @Service用于标注业务层组件@Controller用于标注控制层组件(如struts中的action)@Repository用于标注数 ...
- 73. Spring Boot注解(annotation)列表【从零开始学Spring Boot】
[从零开始学习Spirng Boot-常见异常汇总] 针对于Spring Boot提供的注解,如果没有好好研究一下的话,那么想应用自如Spring Boot的话,还是有点困难的,所以我们这小节,说说S ...
- 框架-Java:Spring Boot
ylbtech-框架-Java:Spring Boot 1.返回顶部 1. Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该 ...
- spring boot注解之@Scheduled定时任务实现
java实现定时任务一般使用timer,或者使用quartz组件.现在在spring boot提供了更加方便的实现方式. spring boot已经集成了定时任务.使用@Secheduled注解. @ ...
- Spring Boot 注解详解
一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration ...
随机推荐
- nyoj 1129 Salvation 模拟
思路:每个坐标有四种状态,每个点对应的每种状态只能走一个方向,如果走到一个重复的状态说明根本不能走到终点,否则继续走即可. 坑点:有可能初始坐标四周都是墙壁,如果不判断下可能会陷入是死循环. 贴上测试 ...
- AGC012 - E: Camel and Oases
原题链接 题意简述 沙漠中有个排成一条直线的绿洲,一头储水量为的骆驼. 骆驼有两个操作: 走到距离在V以内的一个绿洲. 飞到任意一个绿洲,但V减少一半.V=0时不能飞. 问骆驼依次从每个绿洲出发,能否 ...
- SpringBoot,Security4, redis共享session,分布式SESSION并发控制,同账号只能登录一次
由于集成了spring session ,redis 共享session,导致SpringSecurity单节点的session并发控制失效, springSession 号称 无缝整合httpses ...
- Linux sftp 安全文件传输命令
sftp 是一个交互式文件传输程式.它类似于 ftp, 但它进行加密传输,比FTP有更高的安全性. 1.常用登陆方式: 格式:sftp <user>@<host> 通过sftp ...
- git 命令和使用场景总结
资料地址:https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000 http://w ...
- shiro整合ehcache
目标:让Shiro整合ehcache,提供缓存realm数据的功能. 1.引入encache配置文件,配置缓存 <!-- <ehcache xmlns:xsi="http://w ...
- caffe之路-SIGTERM信号捕捉
Caffe在1.0版本仅支持两种信号的处理: 1) SIGHUP 2) SIGINT SIGHUP:caffe接收到此信号后进行snapshot,并不会中断caffe的训练. SIGINT:caffe ...
- SQL 脚本持续收集...
1.复制表 ---sqlserver (包括表结构和表数据) SELECT * INTO TABEL_NEW FROM TABLE_OLD---sqlserver(只复制表结构)CREATE TABL ...
- 常用u-boot命令详解(全) 2
(8) USB 操作指令 指令 功能 usb reset 初始化USB控制器 usb stop [f] 关闭USB控制器 usb tree 已连接的USB设备树 usb info [dev] 显示US ...
- Java Breakpoint
1.错误描述 Java Breakpoint Unable to install breakpoint in com.you.humb.web.commom.dao.impl.ExportDaoImp ...