SpringBoot 注解介绍
-
@SpringBootApplication 包含了
@ComponentScan
@Configuration
@EnableAutoConfiguration
其中@ComponentScan让Spring Boot扫描到Configuration类并把它加入到程序上下文。 -
@ComponentScan 组件扫描,可自动发现和装配一些Bean。
-
@Configuration 等同于Spring的XML配置文件;使用Java代码可以检查类型安全。
-
@EnableAutoConfiguration 自动配置
-
@RestController 该注解是@Controller和@ResponseBody的合集,表示这是个控制器Bean,并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器。
-
@Autowired 自动导入。
-
@PathVariable 获取参数。
-
@JsonBackReference 解决嵌套外链问题。
-
@RepositoryRestResourcepublic 配合spring-boot-starter-data-rest使用。
注解(annotations)详解
@SpringBootApplication
申明让Spring Boot自动给程序进行必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@ResponseBody
表示该方法的返回结果直接写入HTTP Response Body中,一般在异步获取数据时使用,用于构建RESTful的api。
在使用@RequestMapping后,返回值通常解析为跳转路径,加上@ResponseBody后返回结果不会被解析为跳转路径,而是直接写入HTTP Response Body中。
比如异步获取json数据,加上@ResponseBody后,会直接返回json数据。
该注解一般会配合@RequestMapping一起使用。
@RequestMapping(“/test”)
@ResponseBody
public String test(){
return ”ok”;
}
@PostMapping("/login")
public SysResult login(@RequestBody User user){
String token = userService.login(user);
if(token == null){
return SysResult.fail();
}
return SysResult.success(token);
}
@Controller
用于定义控制器类,在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层)
一般这个注解在类中,通常方法需要配合注解@RequestMapping。
@Controller
@RequestMapping(“/demoInfo”)
publicclass DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
// 会使用hello.html或者hello.ftl模板进行渲染显示.
return"/hello";
}
}
@RestController
用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
publicclass DemoController2 {
@RequestMapping("/test")
public String test(){
return"ok";
}
}
@RequestMapping
提供路由信息,负责URL到Controller中的具体函数的映射。
@EnableAutoConfiguration
Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。
例如,如果你的classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库”。
你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。
如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们。
@ComponentScan
我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。可以自动收集所有的Spring组件,包括@Configuration类。
个人理解相当于,如果扫描到有@Component、@Controller、@Service等这些注解的类,并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。
如果没有配置的话,Spring Boot会扫描启动类所在包下以及子包下的使用了@Service、@Repository等注解的类。
@Configuration
从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。
注意:@Configuration注解的配置类有如下要求:
- @Configuration不可以是final类型;
- @Configuration不可以是匿名类;
- 嵌套的configuration必须是静态类。
用@Configuration加载spring
- @Configuration配置spring并启动spring容器
- @Configuration启动容器+@Bean注册Bean
- @Configuration启动容器+@Component注册Bean
- 使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法
- 配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)
@Configuation加载Spring方法
@Configuration配置spring并启动spring容器
@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)
@Configuation总结
@Configuation等价于<Beans> </Beans>
@Bean等价于 <Bean> </Bean>
@Component 等价于<Bean></Bean>
@ComponentScan等价于<context:component-scan base-package=”com.dxz.demo”/>
@Import
用来导入其他配置类。
@ImportResource
用来加载xml配置文件。
@Autowired
自动导入依赖的bean
@Service
一般用于修饰service层的组件
@Repository
使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。
@Bean
用@Bean标注方法等价于XML中配置的bean。
@Bean VS @Component
- 两个注解的结果是相同的,bean都会被添加到Spring上下文中。
- @Component 标注的是类,允许通过自动扫描发现。@Bean需要在配置类@Configuation中使用。
- @Component类使用的方法或字段时不会使用
CGLIB
增强。而在@Configuration类中使用方法或字段时则使用CGLIB
创造协作对象
假设我们需要将一些第三方的库组件装配到应用中或者 我们有一个在多个应用程序中共享的模块,它包含一些服务。并非所有应用都需要它们。
如果在这些服务类上使用@Component
并在应用程序中使用组件扫描,我们最终可能会检测到超过必要的bean
。导致应用程序无法启动
但是我们可以使用 @Bean
来加载
因此,基本上,使用@Bean
将第三方类添加到上下文中。和@Component
,如果它只在你的单个应用程序中
@Value
不通过配置文件的注入属性的情况,通过@Value将外部的值动态注入到Bean中。(注入Spring boot application.properties配置的属性的值)
通过@Value将外部的值动态注入到Bean中,使用的情况有:
- 注入普通字符串
- 注入操作系统属性
- 注入表达式结果
- 注入其他Bean属性:注入beanInject对象的属性another
- 注入文件资源
- 注入URL资源
详细代码见:
@Value("normal")
private String normal; // 注入普通字符串
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName; // 注入操作系统属性
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; //注入表达式结果
@Value("#{beanInject.another}")
private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面
@Value("classpath:com/hry/spring/configinject/config.txt")
private Resource resourceFile; // 注入文件资源
@Value("http://www.baidu.com")
private Resource testUrl; // 注入URL资源
注入其他Bean属性:注入beanInject对象的属性another
@Component
public class BeanInject {
@Value("其他Bean的属性")
private String another;
public String getAnother() {
return another;
}
public void setAnother(String another) {
this.another = another;
}
}
通过配置文件的注入属性的情况
通过@Value将外部配置文件的值动态注入到Bean中。配置文件主要有两类:
-
application.properties。
application.properties在spring boot启动时默认加载此文件 -
自定义属性文件
自定义属性文件通过@PropertySource加载。
@PropertySource可以同时加载多个文件,也可以加载单个文件。
如果相同第一个属性文件和第二属性文件存在相同key,则最后一个属性文件里的key启作用。加载文件的路径也可以配置变量,如下文的${anotherfile.configinject},此值定义在第一个属性文件config.properties
第一个属性文件config.properties内容如下:
${anotherfile.configinject}作为第二个属性文件加载路径的变量值
book.name=bookName
anotherfile.configinject=placeholder
第二个属性文件config_placeholder.properties内容如下:
book.name.placeholder=bookNamePlaceholder
下面通过@Value(“${app.name}”)语法将属性文件的值注入bean属性值,详细代码见:
@Component
// 引入外部配置文件组:${app.configinject}的值来自config.properties。
// 如果相同
@PropertySource({"classpath:com/hry/spring/configinject/config.properties",
"classpath:com/hry/spring/configinject/config_${anotherfile.configinject}.properties"})
public class ConfigurationFileInject{
@Value("${app.name}")
private String appName; // 这里的值来自application.properties,spring boot启动时默认加载此文件
@Value("${book.name}")
private String bookName; // 注入第一个配置外部文件属性
@Value("${book.name.placeholder}")
private String bookNamePlaceholder; // 注入第二个配置外部文件属性
@Autowired
private Environment env; // 注入环境变量对象,存储注入的属性值
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("bookName=").append(bookName).append("\r\n")
.append("bookNamePlaceholder=").append(bookNamePlaceholder).append("\r\n")
.append("appName=").append(appName).append("\r\n")
.append("env=").append(env).append("\r\n")
// 从eniroment中获取属性值
.append("env=").append(env.getProperty("book.name.placeholder")).append("\r\n");
return sb.toString();
}
}
@Inject
等价于默认的@Autowired,只是没有required属性;
@Component
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Bean
相当于XML中的,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。
@AutoWired
自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。当加上(required=false)时,就算找不到bean也不报错。
@Qualifier
当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:
@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
@Resource(name=”name”,type=”type”)
没有括号内内容的话,默认byName。与@Autowired干类似的事。
JPA(Java持久层API)注解
@Entity @Table(name=”“):
表明这是一个实体类。一般用于jpa这两个注解一般一块使用,但是如果表名和实体类名相同的话,@Table可以省略。
@MappedSuperClass
用在确定是父类的entity上。父类的属性子类可以继承。
@NoRepositoryBean
一般用作父类的repository,有这个注解,Spring不会去实例化该repository。
@Column
如果字段名与列名相同,则可以省略。
@I
表示该属性为主键。
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator= “repair_seq”)
表示主键生成策略是sequence(可以为Auto、IDENTITY、native等,Auto表示可在多个数据库间切换),指定sequence的名字是repair_seq。
@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1)
name为sequence的名称,以便使用,sequenceName为数据库的sequence名称,两个名称可以一致。
@Transient
表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。
如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basic。
@Basic(fetch=FetchType.LAZY)
标记可以指定实体属性的加载方式。
@JsonIgnore
作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响。
@JoinColumn(name=”loginId”)
一对一:本表中指向另一个表的外键。一对多:另一个表指向本表的外键。
@OneToOne、@OneToMany、@ManyToOne
对应hibernate配置文件中的一对一,一对多,多对一。
全局异常处理
@ControllerAdvice
包含@Component。可以被扫描到。统一处理异常。
@ExceptionHandler(Exception.class)
用在方法上面表示遇到这个异常就执行以下方法。