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 ...
随机推荐
- openresty 中mime.types 文件缺失问题,无法展示图片
看技术群有人问这个:"图片不展示了,直接下载了,怎么设置nginx",之前刚开始学习nginx时遇到过,然后 使用 openresty+lua在做网关时遇到过,这里还是记录下吧. ...
- 情景linux--如何解决read命令产生的硬编码问题
情景 我们知道,read命令可以读取文件内容,并把内容赋值给变量. 以如下的数据文件为例. $ cat data.txt 1 201623210021 wangzhiguo 25 2 20162321 ...
- 内置函数--global() 和 local()
一 . globals :返回当前作用域内全局变量的字典. >>> globals() {'__spec__': None, '__package__': None, '__bu ...
- Spring MVC处理(下周完善)
http://www.cnblogs.com/xiepeixing/p/4244574.html http://blog.csdn.net/kobejayandy/article/details/12 ...
- dojo级联步骤
dojo级联步骤 1.数据请求回来后,检查数据格式是否满足下拉框的数据格式: 2.通过firebug进行调试,检查select下拉框子项结点是否取道: 3.查看API文档,保证改变store的方法是正 ...
- 项目部署到Tomcat报错
1.今天晚上,我想把dojo项目部署到Tomcat中,结果发现部署不了,Tomcat报错.而且,这个错误白天时也碰到了. 错误具体详细如下: Publishing failed with multip ...
- VxWorks 引导程序
前言:vxworks 的一些文件,如 usrconfig.c 在 config,comp目录中均有出现,因编译方式而选择某一个文件,命令行方式采用 config 目录文件,tornado 图形界面配置 ...
- Python Numpy包安装
1,下载python 下载地址: https://www.python.org/downloads/windows/ 2,配置python环境变量 在电脑的系统属性的系统变量path中添加python ...
- Eclipse设置内存大小
Eclipse设置内存大小 1.修改Eclipse的配置文件 (1)打开Eclipse目录 (2)以EditPlus打开eclipse.ini,修改"-Xms40m -Xmx512m&qu ...
- Unity3d开发中与oc交互之类型转换
对于非科班出身的程序来说,在没有学过C和OC的情况,用unity开发iOS相关的功能,是非常痛苦的.简单写一下自己遇到的,并且没有百度到的坑. 1.C#给OC传递字典 一般流程是,C#调用C,C调用O ...