@RequestParam 有三个属性:
(1)value:请求参数名(必须配置)
(2)required:是否必需,默认为 true,即 请求中必须包含该参数,如果
没有包含,将会抛出异常(可选配置)
(3)defaultValue:默认值,如果设置了该值,required 将自动设为 false,
无论你是否配置了required,配置了什么值,都是 false(可选配置)
一,注解(注释)列表
@SpringBootApplication:包含了@ComponeScan,@ Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让spring启动扫描到配置类并将它加入到程序上下文。
@Configuration等同于spring的XML配置文件;使用Java代码可以检查类型安全。
@EnableAutoConfiguration自动配置。
@ComponentScan组件扫描,可自动发现和装配一些Bean。
@Component可配合CommandLineRunner使用,在程序启动后执行一些基础任务。
@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将要函数的返回值直接填入HTTP响应体中,是REST风格的控制器。
@Autowired自动导入。
@PathVariable获取参数。
@JsonBackReference解决嵌套外链问题。
@RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。
二、注解(annotations)详解
@SpringBootApplication:申明让spring boot自动给程序进行必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。
1 package com.example.myproject;
2 import org.springframework.boot.SpringApplication;
3 import org.springframework.boot.autoconfigure.SpringBootApplication;
4
5 @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
6 public class Application {
7 public static void main(String[] args) {
8 SpringApplication.run(Application.class, args);
9 }
10 }
@ ResponseBody:表示该方法的返回结果直接写入HTTP响应体中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping后,返回值通常解析为跳转路径,加上@ Responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP响应体中。比如异步获取json数据,加上@ Responsebody后,会直接返回json数据。该注解一般会配合@RequestMapping一起使用示例代码:
1 @RequestMapping(“/test”)
2 @ResponseBody
3 public String test(){
4 return”ok”;
5 }
@Controller:用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping。示例代码:
1 @Controller
2 @RequestMapping(“/demoInfo”)
3 public class DemoController {
4 @Autowired
5 private DemoInfoService demoInfoService;
6
7 @RequestMapping("/hello")
8 public String hello(Map<String,Object> map){
9 System.out.println("DemoController.hello()");
10 map.put("hello","from TemplateController.helloHtml");
11 //会使用hello.html或者hello.ftl模板进行渲染显示.
12 return"/hello";
13 }
14 }
@RestController:用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集。示例代码:
1 package com.kfit.demo.web;
2
3 import org.springframework.web.bind.annotation.RequestMapping;
4 import org.springframework.web.bind.annotation.RestController;
5
6
7 @RestController
8 @RequestMapping(“/demoInfo2”)
9 publicclass DemoController2 {
10
11 @RequestMapping("/test")
12 public String test(){
13 return "ok";
14 }
15 }
@RequestMapping:提供路由信息,负责URL到Controller中的具体函数的映射。
@EnableAutoConfiguration:SpringBoot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。例如,如果你的classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库”。你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们。
@ComponentScan:表示将该类自动发现扫描组件。个人理解相当于,如果扫描到有@Component、@Controller、@Service等这些注解的类,并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。可以自动收集所有的Spring组件,包括@Configuration类。我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。如果没有配置的话,Spring Boot会扫描启动类所在包下以及子包下的使用了@Service,@Repository等注解的类。
@Configuration:相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。
@Import:用来导入其他配置类。
@ImportResource:用来加载xml配置文件。
@Autowired:自动导入依赖的bean
@Service:一般用于修饰service层的组件
@Repository:使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。
@Bean:用@Bean标注方法等价于XML中配置的bean。
@Value:注入Spring boot application.properties配置的属性的值。示例代码:
1 @Value(value = “#{message}”)
2 private String message;
@Inject:等价于默认的@Autowired,只是没有required属性;
@Component:泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Bean:相当于XML中的,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。
@AutoWired:自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。当加上(required=false)时,就算找不到bean也不报错。
@Qualifier:当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:
1 @Autowired
2 @Qualifier(value = “demoInfoService”)
3 private DemoInfoService demoInfoService;
@Resource(name=”name”,type=”type”):没有括号内内容的话,默认byName。与@Autowired干类似的事。
三、JPA注解
@Entity:@Table(name=”“):表明这是一个实体类。一般用于jpa这两个注解一般一块使用,但是如果表名和实体类名相同的话,@Table可以省略
@MappedSuperClass:用在确定是父类的entity上。父类的属性子类可以继承。
@NoRepositoryBean:一般用作父类的repository,有这个注解,spring不会去实例化该repository。
@Column:如果字段名与列名相同,则可以省略。
@Id:表示该属性为主键。
@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配置文件中的一对一,一对多,多对一。
四、springMVC相关注解
@RequestMapping:@RequestMapping(“/path”)表示该控制器处理所有“/path”的UR L请求。RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。
用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。该注解有六个属性:
params:指定request中必须包含某些参数值是,才让该方法处理。
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
value:指定请求的实际地址,指定的地址可以是URI Template 模式
method:指定请求的method类型, GET、POST、PUT、DELETE等
consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html;
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回
@RequestParam:用在方法的参数前面。
@RequestParam
String a =request.getParameter(“a”)。
@PathVariable:路径变量。如
1 RequestMapping(“user/get/mac/{macAddress}”)
2 public String getByMacAddress(@PathVariable String macAddress){
3 //do something;
4 }
参数与大括号里的名字一样要相同。
五、全局异常处理
@ControllerAdvice:包含@Component。可以被扫描到。统一处理异常。
@ExceptionHandler(Exception.class):用在方法上面表示遇到这个异常就执行以下方法。
六、项目中具体配置解析和使用环境
@MappedSuperclass:
1.@MappedSuperclass 注解使用在父类上面,是用来标识父类的
2.@MappedSuperclass 标识的类表示其不能映射到数据库表,因为其不是一个完整的实体类,但是它所拥有的属性能够映射在其子类对用的数据库表中
3.@MappedSuperclass 标识的类不能再有@Entity或@Table注解
@Column:
1.当实体的属性与其映射的数据库表的列不同名时需要使用@Column标注说明,该属性通常置于实体的属性声明语句之前,还可与 @Id 标注一起使用。
2.@Column 标注的常用属性是name,用于设置映射数据库表的列名。此外,该标注还包含其它多个属性,如:unique、nullable、length、precision等。具体如下:
1 name属性:name属性定义了被标注字段在数据库表中所对应字段的名称
2 unique属性:unique属性表示该字段是否为唯一标识,默认为false,如果表中有一个字段需要唯一标识,则既可以使用该标记,也可以使用@Table注解中的@UniqueConstraint
3 nullable属性:nullable属性表示该字段是否可以为null值,默认为true
4 insertable属性:insertable属性表示在使用”INSERT”语句插入数据时,是否需要插入该字段的值
5 updateable属性:updateable属性表示在使用”UPDATE”语句插入数据时,是否需要更新该字段的值
6 insertable和updateable属性:一般多用于只读的属性,例如主键和外键等,这些字段通常是自动生成的
7 columnDefinition属性:columnDefinition属性表示创建表时,该字段创建的SQL语句,一般用于通过Entity生成表定义时使用,如果数据库中表已经建好,该属性没有必要使用
8 table属性:table属性定义了包含当前字段的表名
9 length属性:length属性表示字段的长度,当字段的类型为varchar时,该属性才有效,默认为255个字符
10 precision属性和scale属性:precision属性和scale属性一起表示精度,当字段类型为double时,precision表示数值的总长度,scale表示小数点所占的位数
具体如下:
1.double类型将在数据库中映射为double类型,precision和scale属性无效
2.double类型若在columnDefinition属性中指定数字类型为decimal并指定精度,则最终以columnDefinition为准
3.BigDecimal类型在数据库中映射为decimal类型,precision和scale属性有效
4.precision和scale属性只在BigDecimal类型中有效
3.@Column 标注的columnDefinition属性: 表示该字段在数据库中的实际类型.通常 ORM 框架可以根据属性类型自动判断数据库中字段的类型,但是对于Date类型仍无法确定数据库中字段类型究竟是DATE,TIME还是TIMESTAMP.此外,String的默认映射类型为VARCHAR,如果要将 String 类型映射到特定数据库的 BLOB 或TEXT字段类型.
4.@Column标注也可置于属性的getter方法之前
@Getter和@Setter(Lombok)
@Setter:注解在属性上;为属性提供 setting 方法 @Getter:注解在属性上;为属性提供 getting 方法
扩展:
1 @Data:注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
2
3 @Setter:注解在属性上;为属性提供 setting 方法
4
5 @Getter:注解在属性上;为属性提供 getting 方法
6
7 @Log4j2 :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象,和@Log4j注解类似
8
9 @NoArgsConstructor:注解在类上;为类提供一个无参的构造方法
10
11 @AllArgsConstructor:注解在类上;为类提供一个全参的构造方法
12
13 @EqualsAndHashCode:默认情况下,会使用所有非瞬态(non-transient)和非静态(non-static)字段来生成equals和hascode方法,也可以指定具体使用哪些属性。
14
15 @toString:生成toString方法,默认情况下,会输出类名、所有属性,属性会按照顺序输出,以逗号分割。
16
17 @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
18 无参构造器、部分参数构造器、全参构造器,当我们需要重载多个构造器的时候,只能自己手写了
19
20 @NonNull:注解在属性上,如果注解了,就必须不能为Null
21
22 @val:注解在属性上,如果注解了,就是设置为final类型,可查看源码的注释知道
@PreUpdate和@PrePersist
@PreUpdate
1.用于为相应的生命周期事件指定回调方法。
2.该注释可以应用于实体类,映射超类或回调监听器类的方法。
3.用于setter 如果要每次更新实体时更新实体的属性,可以使用@PreUpdate注释。
4.使用该注释,您不必在每次更新用户实体时显式更新相应的属性。
5.preUpdate不允许您更改您的实体。 您只能使用传递给事件的计算的更改集来修改原始字段值。
@Prepersist
1.查看@PrePersist注释,帮助您在持久化之前自动填充实体属性。
2.可以用来在使用jpa的时记录一些业务无关的字段,比如最后更新时间等等。生命周期方法注解(delete没有生命周期事件)
3.@PrePersist save之前被调用,它可以返回一个DBObject代替一个空的 @PostPersist save到datastore之后被调用
4.@PostLoad 在Entity被映射之后被调用 @EntityListeners 指定外部生命周期事件实现类
实体Bean生命周期的回调事件
方法的标注: @PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad 。
它们标注在某个方法之前,没有任何参数。这些标注下的方法在实体的状态改变前后时进行调用,相当于拦截器;
pre 表示在状态切换前触发,post 则表示在切换后触发。
@PostLoad 事件在下列情况触发:
1. 执行 EntityManager.find()或 getreference()方法载入一个实体后;
2. 执行 JPA QL 查询过后;
3. EntityManager.refresh( )方法被调用后。
@PrePersist 和 @PostPersist事件在实体对象插入到数据库的过程中发生;
@PrePersist 事件在调用 EntityManager.persist()方法后立刻发生,级联保存也会发生此事件,此时的数据还没有真实插入进数据库。
@PostPersist 事件在数据已经插入进数据库后发生。
@PreUpdate 和 @PostUpdate 事件的触发由更新实体引起, @PreUpdate 事件在实体的状态同步到数据库之前触发,此时的数据还没有真实更新到数据库。
@PostUpdate 事件在实体的状态同步到数据库后触发,同步在事务提交时发生。
@PreRemove 和 @PostRemove 事件的触发由删除实体引起,@ PreRemove 事件在实体从数据库删除之前触发,即调用了 EntityManager.remove()方法或者级联删除
当你在执行各种持久化方法的时候,实体的状态会随之改变,状态的改变会引发不同的生命周期事件。这些事件可以使用不同的注释符来指示发生时的回调函数。
@javax.persistence.PostLoad:加载后。
@javax.persistence.PrePersist:持久化前。
@javax.persistence.PostPersist:持久化后。
@javax.persistence.PreUpdate:更新前。
@javax.persistence.PostUpdate:更新后。
@javax.persistence.PreRemove:删除前。
@javax.persistence.PostRemove:删除后。
1)数据库查询
@PostLoad事件在下列情况下触发:
执行EntityManager.find()或getreference()方法载入一个实体后。
执行JPQL查询后。
EntityManager.refresh()方法被调用后。
2)数据库插入
@PrePersist和@PostPersist事件在实体对象插入到数据库的过程中发生:
@PrePersist事件在调用坚持()方法后立刻发生,此时的数据还没有真正插入进数据库。
@PostPersist事件在数据已经插入进数据库后发生。
3)数据库更新
@PreUpdate和@PostUpdate事件的触发由更新实体引起:
@PreUpdate事件在实体的状态同步到数据库之前触发,此时的数据还没有真正更新到数据库。
@PostUpdate事件在实体的状态同步到数据库之后触发,同步在事务提交时发生。
4)数据库删除
@PreRemove和@PostRemove事件的触发由删除实体引起:
@PreRemove事件在实体从数据库删除之前触发,即在调用删除()方法删除时发生,此时的数据还没有真正从数据库中删除。
@PostRemove事件在实体从数据库中删除后触发。
@NoArgsConstructor&@AllArgsConstructor(lombok)
@NoArgsConstructor,提供一个无参的构造方法。
@AllArgsConstructor,提供一个全参的构造方法。
@Configuration & @bean
<beans>
1 package com.test.spring.support.configuration;
2
3 @Configuration
4 public class TestConfiguration {
5 public TestConfiguration(){
6 System.out.println("spring容器启动初始化。。。");
7 }
8 }
相当于:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
4 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
5 xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
6 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
8 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
9 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
10 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
11 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
12 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
13
14
15 </beans>
主方法进行测试:
1 package com.test.spring.support.configuration;
2
3 public class TestMain {
4 public static void main(String[] args) {
5
6 //@Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
7 ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
8
9 //如果加载spring-context.xml文件:
10 //ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
11 }
12 }
从运行主方法结果可以看出,春季容器已经启动了:
1 八月 11, 2016 12:04:11 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
2 信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@203e25d3: startup date [Thu Aug 11 12:04:11 CST 2016]; root of context hierarchy
3 spring容器启动初始化。。。
2. @豆标注在方法上(返回某个实例的方法),等价于弹簧的XML配置文件中的<bean>
,作用为:注册豆对象
豆类:
1 package com.test.spring.support.configuration;
2
3 public class TestBean {
4
5 public void sayHello(){
6 System.out.println("TestBean sayHello...");
7 }
8
9 public String toString(){
10 return "username:"+this.username+",url:"+this.url+",password:"+this.password;
11 }
12
13 public void start(){
14 System.out.println("TestBean 初始化。。。");
15 }
16
17 public void cleanUp(){
18 System.out.println("TestBean 销毁。。。");
19 }
20 }
配置类:
1 package com.test.spring.support.configuration;
2
3 @Configuration
4 public class TestConfiguration {
5 public TestConfiguration(){
6 System.out.println("spring容器启动初始化。。。");
7 }
8
9 //@Bean注解注册bean,同时可以指定初始化和销毁方法
10 //@Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")
11 @Bean
12 @Scope("prototype")
13 public TestBean testBean() {
14 return new TestBean();
15 }
16 }
主方法测试类:
1 package com.test.spring.support.configuration;
2
3 public class TestMain {
4 public static void main(String[] args) {
5 ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
6 //获取bean
7 TestBean tb = context.getBean("testBean");
8 tb.sayHello();
9 }
10 }
注:
(1),@ Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同;
(2),@ Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域;
(3),既然@Bean的作用是注册bean对象,那么完全可以使用@Component,@ Controller,@ Service,@ Ripository等注解注册bean ,当然需要配置@ComponentScan注解进行自动扫描。
豆类:
1 package com.test.spring.support.configuration;
2
3 //添加注册bean的注解
4 @Component
5 public class TestBean {
6
7 public void sayHello(){
8 System.out.println("TestBean sayHello...");
9 }
10
11 public String toString(){
12 return "username:"+this.username+",url:"+this.url+",password:"+this.password;
13 }
14 }
配置类:
1 //开启注解配置
2 @Configuration
3 //添加自动扫描注解,basePackages为TestBean包路径
4 @ComponentScan(basePackages = "com.test.spring.support.configuration")
5 public class TestConfiguration {
6 public TestConfiguration(){
7 System.out.println("spring容器启动初始化。。。");
8 }
9
10 //取消@Bean注解注册bean的方式
11 //@Bean
12 //@Scope("prototype")
13 //public TestBean testBean() {
14 // return new TestBean();
15 //}
16 }
主方法测试获取的bean对象:
1 public class TestMain {
2 public static void main(String[] args) {
3 ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
4 //获取bean
5 TestBean tb = context.getBean("testBean");
6 tb.sayHello();
7 }
8 }
的sayHello()方法都被正常调用。
使用@Configuration注解来代替弹簧的bean的配置
下面是一个典型的春天配置文件(应用程序-config.xml中):
1 <beans>
2 <bean id="orderService" class="com.acme.OrderService"/>
3 <constructor-arg ref="orderRepository"/>
4 </bean>
5 <bean id="orderRepository" class="com.acme.OrderRepository"/>
6 <constructor-arg ref="dataSource"/>
7 </bean>
8 </beans>
然后你就可以像这样来使用是豆了:
1 ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
2 OrderService orderService = (OrderService) ctx.getBean("orderService");
现在Spring Java配置这个项目提供了一种通过java代码来装配bean的方案:
1 @Configuration
2 public class ApplicationConfig {
3
4 public @Bean OrderService orderService() {
5 return new OrderService(orderRepository());
6 }
7
8 public @Bean OrderRepository orderRepository() {
9 return new OrderRepository(dataSource());
10 }
11
12 public @Bean DataSource dataSource() {
13 // instantiate and return an new DataSource …
14 }
15 }
然后你就可以像这样来使用是豆了:
1 JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);
2 OrderService orderService = ctx.getBean(OrderService.class);
这么做有什么好处呢?
1.使用纯的java代码,不在需要XML
2.在配置中也可享受OO带来的好处(面向对象)
3.类型安全对重构也能提供良好的支持
4.减少复杂配置文件的同时依旧能享受到所有springIoC容器提供的功能
@Configuration可理解为用spring的时候xml里面的<beans>标签
@Bean可理解为用spring的时候xml里面的<bean>标签
(原文地址:https://blog.csdn.net/u012260707/article/details/52021265)
1、@controller 控制器(注入服务)
2、@service 服务(注入dao)
3、@repository dao(实现dao访问)
4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>))(原文地址:https://blog.csdn.net/thinkingcao/article/details/71171222)
@MappedSuperclass 标注为@MappedSuperclass的类将不是一个完整的实体类,他将不会映射到数据库表,但是他的属性都将映射到其子类的数据库字段中。(原文地址:http://blog.sina.com.cn/s/blog_7085382f0100uk4p.html)
@GeneratedValue PA的@GeneratedValue注解,在JPA中,@GeneratedValue注解存在的意义主要就是为一个实体生成一个唯一标识的主键(原文地址:https://blog.csdn.net/u012493207/article/details/50846616)
@profile 例如在开发环境与生产环境使用不同的参数,可以配置两套配置文件,通过@profile来激活需要的环境(原文地址:https://blog.csdn.net/hj7jay/article/details/53634159)
@Intercepts Mybatis的插件都要有Intercepts注解来指定要拦截哪个对象的哪个方法。(原文地址:https://www.jianshu.com/p/7c7b8c2c985d https://blog.csdn.net/yhjyumi/article/details/49188051)
@ExceptionHandler @ControllerAdvice 用于异常 (原味地址:https://blog.csdn.net/w372426096/article/details/78429141 https://blog.csdn.net/w372426096/article/details/78429132?utm_source=blogxgwz3)
@RestController 表示这个类返回的都是json数据 (地址:https://www.cnblogs.com/shuaifing/p/8119664.html)
==================================================
@Column(unique = true)
详细解释:
-
unique=true是指这个字段的值在这张表里不能重复,所有记录值都要唯一,就像主键那样。
-
nullable=false是这个字段在保存时必需有值,不能还是null值就调用save去保存入库。
-
这两个用法是不同的,需要看个人需要,互相不可取代,根据个人需要可以两个都设置也可以只设置其中一个。
-
hibernate常用方法介绍:
-
delete(Object entity) 删除指定的持久化实例在程序中一般先用 Assert.notNull和 Assert.isTrue断言entity是否为空 和 entity的id是否大于0,否则事务回滚。再用get(Class entityClass,Serializable id,LockMode lockMode)加锁查询出持久化实例,一般用lockMode.update悲观锁,最后用delete(Object entity)来删除此实例。
-
deleteAll(Collection entities) 删除集合内全部持久化实例entities必须为持久化实例,否则报数据库异常错误。
-
find(String queryString) 根据HQL查询字符串来返回实例集合find方法在执行时会先查找缓存,如果缓存找不到再查找数据库,如果再找不到就会返回null。
-
get(Class entityClass,Serializable id)根据主键加载特定持久化实例在程序中一般先用 Assert.isTrue断言id是否大于0,若大于0继续执行,若查到数据则返回实例,否则返回空不同于load,load若有数据则返回实例,否则报出ObjectNotFoundEcception异常,相比来说get效率高些。
-
save(Object entity) 保存新的实例,在程序中一般先用 Assert.notNull断言实体是否为空,在进行保存。
==================================================
=====================================================
Swagger 注解 Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。
(原文地址: https://www.jianshu.com/p/8033ef83a8ed | https://blog.csdn.net/xupeng874395012/article/details/68946676/ | https://blog.csdn.net/java_yes/article/details/79183804 | https://blog.csdn.net/y_hai_yang/article/details/77839447 )
@Api:
作用在类上,用来标注该类具体实现内容。表示标识这个类是swagger的资源 。
参数:
1. tags:可以使用tags()允许您为操作设置多个标签的属性,而不是使用该属性。
2. description:可描述描述该类作用。
@ApiImplicitParam:
作用在方法上,表示单独的请求参数
参数:
1. name :参数名。
2. value : 参数的具体意义,作用。
3. required : 参数是否必填。
4. dataType :参数的数据类型。
5. paramType :查询参数类型,这里有几种形式:
在这里我被坑过一次:当我发POST请求的时候,当时接受的整个参数,不论我用body还是query,后台都会报Body Missing错误。这个参数和SpringMvc中的@RequestBody冲突,索性我就去掉了paramType,对接口测试并没有影响。
@ApiImplicitParams:
用于方法,包含多个 @ApiImplicitParam
@ApiModel:
用于类,表示对类进行说明,用于参数用实体类接收;
@ApiModelProperty:
用于方法,字段 ,表示对model属性的说明或者数据操作更改
@ApiOperation:
用于方法,表示一个http请求的操作 。
@ApiResponse:
用于方法,描述操作的可能响应。
@ApiResponses:
用于方法,一个允许多个ApiResponse对象列表的包装器。
@ApiParam:
用于方法,参数,字段说明,表示对参数的添加元数据(说明或是否必填等)
@Authorization:
声明要在资源或操作上使用的授权方案。
@AuthorizationScope:
介绍一个OAuth2授权范围。
@ResponseHeader:
响应头设置,使用方法。
1. api标记
Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:
@Api(value = "/user", description = "Operations about user")
与Controller注解并列使用。 属性配置:
属性名称 | 备注 |
---|---|
value | url的路径值 |
tags | 如果设置这个值、value的值会被覆盖 |
description | 对api资源的描述 |
basePath | 基本路径可以不配置 |
position | 如果配置多个Api 想改变显示的顺序位置 |
produces | For example, "application/json, application/xml" |
consumes | For example, "application/json, application/xml" |
protocols | Possible values: http, https, ws, wss. |
authorizations | 高级特性认证时配置 |
hidden | 配置为true 将在文档中隐藏 |
在SpringMvc中的配置如下:
@Controller
@RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
@Api(value = "/pet", description = "Operations about pets")
public class PetController {
}
2. ApiOperation标记
ApiOperation:用在方法上,说明方法的作用,每一个url资源的定义,使用方式:
@ApiOperation(
value = "Find purchase order by ID",
notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
response = Order,
tags = {"Pet Store"})
与Controller中的方法并列使用。
属性配置:
属性名称 | 备注 |
---|---|
value | url的路径值 |
tags | 如果设置这个值、value的值会被覆盖 |
description | 对api资源的描述 |
basePath | 基本路径可以不配置 |
position | 如果配置多个Api 想改变显示的顺序位置 |
produces | For example, "application/json, application/xml" |
consumes | For example, "application/json, application/xml" |
protocols | Possible values: http, https, ws, wss. |
authorizations | 高级特性认证时配置 |
hidden | 配置为true 将在文档中隐藏 |
response | 返回的对象 |
responseContainer | 这些对象是有效的 "List", "Set" or "Map".,其他无效 |
httpMethod | "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH" |
code | http的状态码 默认 200 |
extensions | 扩展属性 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order/{orderId}", method = GET)
@ApiOperation(
value = "Find purchase order by ID",
notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
response = Order.class,
tags = { "Pet Store" })
public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId)
throws NotFoundException {
Order order = storeData.get(Long.valueOf(orderId));
if (null != order) {
return ok(order);
} else {
throw new NotFoundException(404, "Order not found");
}
}
3. ApiParam标记
ApiParam请求属性,使用方式:
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)
与Controller中的方法并列使用。
属性配置:
属性名称 | 备注 |
---|---|
name | 属性名称 |
value | 属性值 |
defaultValue | 默认属性值 |
allowableValues | 可以不配置 |
required | 是否属性必填 |
access | 不过多描述 |
allowMultiple | 默认为false |
hidden | 隐藏该属性 |
example | 举例子 |
在SpringMvc中的配置如下:
public ResponseEntity<Order> getOrderById(
@ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)
@PathVariable("orderId") String orderId)
4. ApiResponse
ApiResponse:响应配置,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")
与Controller中的方法并列使用。 属性配置:
属性名称 | 备注 |
---|---|
code | http的状态码 |
message | 描述 |
response | 默认响应类 Void |
reference | 参考ApiOperation中配置 |
responseHeaders | 参考 ResponseHeader 属性配置说明 |
responseContainer | 参考ApiOperation中配置 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
storeData.add(order);
return ok("");
}
5. ApiResponses
ApiResponses:响应集配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
与Controller中的方法并列使用。 属性配置:
属性名称 | 备注 |
---|---|
value | 多个ApiResponse配置 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
storeData.add(order);
return ok("");
}
6. ResponseHeader
响应头设置,使用方法
@ResponseHeader(name="head1",description="response head conf")
与Controller中的方法并列使用。 属性配置:
属性名称 | 备注 |
---|---|
name | 响应头名称 |
description | 头描述 |
response | 默认响应类 Void |
responseContainer | 参考ApiOperation中配置 |
在SpringMvc中的配置如下:
@ApiModel(description = "群组")
7. 其他
- @ApiImplicitParams:用在方法上包含一组参数说明;
- @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
- paramType:参数放在哪个地方
- name:参数代表的含义
- value:参数名称
- dataType: 参数类型,有String/int,无用
- required : 是否必要
- defaultValue:参数的默认值
- @ApiResponses:用于表示一组响应;
- @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息;
- code: 响应码(int型),可自定义
- message:状态码对应的响应信息
- @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候;
- @ApiModelProperty:描述一个model的属性
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。Swagger的目标是对REST API定义一个标准的和语言无关的接口,可让人和计算机无需访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过Swagger进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger消除了调用服务时可能会有的猜测。
关于Swagger的集成请参考:https://github.com/yinjihuan/spring-boot-starter-swagger
API
@Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式如下:
@Api(value="企业用户控制器", tags={"用户接口"})
@RestController
@RequestMapping("/user")
public class EnterpriseProductUserController {
}
效果图如下:
value:接口说明
tags:接口说明,可以在页面中显示。可以配置多个,当配置多个的时候,在页面中会显示多个接口的信息
ApiModel
@ApiModel用在类上,表示对类进行说明,用于实体类中的参数接收说明,使用方式如下:
@ApiModel(value = "com.fangjia.fsh.user.query.LoginQuery", description = "登录参数")
public class LoginQuery {
}
效果图如下:
ApiModelProperty
@ApiModelProperty()用于字段,表示对model属性的说明,使用方式如下:
@ApiModel(value = "com.fangjia.fsh.user.query.LoginQuery", description = "登录参数")
public class LoginQuery {
@ApiModelProperty(value = "企业编号", required = true)
private Long eid;
@ApiModelProperty(value = "用户编号", required = true)
private String uid;
}
效果图如下:
ApiParam
@ ApiParam用于Controller中方法的参数说明,使用方式如下:
@PostMapping("/login")
public ResponseData login(@ApiParam(value = "登录参数", required = true) @RequestBody LoginQuery query) {
}
效果图如下:
- value:参数说明
- required:是否必填
ApiOperation
@ApiOperation用在Controller里的方法上,说明方法的作用,每一个接口的定义,使用方式如下:
@ApiOperation(value = "用户登录", notes = "企业用户认证接口,参数为必填项")
@PostMapping("/login")
public ResponseData login(@ApiParam(value = "登录参数", required = true) @RequestBody LoginQuery query) {
}
效果图如下:
value:接口名称
notes:详细说明
ApiResponse和ApiResponses
@ApiResponse用于方法上,说明接口响应的一些信息,@ApiResponses组装多个@ApiResponse,使用方式如下:
@ApiResponses({ @ApiResponse(code = 403, message = "无权限访问") })
public ResponseData login(@ApiParam(value = "登录参数", required = true) @RequestBody LoginQuery query) {
}
效果图如下:
code:响应状态码
message:状态码对应的说明
ApiImplicitParam和ApiImplicitParams
用于方法上,为单独的请求参数进行说明,使用方式如下:
@ApiImplicitParams({
@ApiImplicitParam(name="uid", value="用户ID", required=true, paramType="query", dataType="String", defaultValue="1")
})
@GetMapping("/hello")
public String hello(String uid) {
return uid;
}
效果图如下:
name:参数名,对应方法中单独的参数名称
value:参数中文说明
required:是否必填
paramType:参数类型,取值为path, query, body, header, form
dataType:参数数据类型
defaultValue:默认值
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="用户名",name="username",example="xingguo")
private String username;
@ApiModelProperty(value="状态",name="state",required=true)
private Integer state;
private String password;
private String nickName;
private Integer isDeleted;
@ApiModelProperty(value="id数组",hidden=true)
private String[] ids;
private List<String> idList;
//省略get/set
======================================================
@CrossOrigin @CrossOrigin可以处理跨域请求,让你能访问不是一个域的文件。 (原文地址:https://blog.csdn.net/zjy15203167987/article/details/77330992 | https://www.cnblogs.com/mmzs/p/9167743.html)
@Validated 验证,校验的错误信息 (原文地址: https://blog.csdn.net/qq_15037231/article/details/80583839?utm_source=blogxgwz7 | https://blog.csdn.net/LittleSkey/article/details/52224352 | https://blog.csdn.net/zhenwei1994/article/details/81460419 | https://blog.csdn.net/gaojp008/article/details/80583301)
@Entity 对实体注释。任何Hibernate映射对象都要有这个注释
@Table 声明此对象映射到数据库的数据表,通过它可以为实体指定表(talbe),目录(Catalog)和schema的名字。该注释不是必须的,如果没有则系统使用默认值(实体的短类名)。
@Version 该注释可用于在实体Bean中添加乐观锁支持。
@Column 就像@Table注解用来标识实体类与数据表的对应关系类似,@Column注解来标识实体类中属性与数据表中字段的对应关系。(原文地址:https://blog.csdn.net/qq_16769857/article/details/80347459 | https://blog.csdn.net/TuxedoLinux/article/details/80875261?utm_source=blogxgwz0)
===================================================
lombok 注解 (注解介绍地址:https://blog.csdn.net/sunsfan/article/details/53542374)
@Data 注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
@Setter :注解在属性上;为属性提供 setting 方法
@Setter :注解在属性上;为属性提供 getting 方法
@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象
@Slf4j : 注解在类上, 为类提供一个属性名为 log 的 log4j 的日志对象
@NoArgsConstructor :注解在类上;为类提供一个无参的构造方法
@AllArgsConstructor :注解在类上;为类提供一个全参的构造方法
@Cleanup : 可以关闭流
@Builder : 被注解的类加个构造者模式
@Synchronized : 加个同步锁
@SneakyThrows : 等同于try/catch 捕获异常
@NonNull : 如果给参数加个这个注解 参数为null会抛出空指针异常
@Value : 注解和@Data类似,区别在于它会把所有成员变量默认定义为private final修饰,并且不会生成set方法。
@ToString/@EqualsAndHashCode
这两个注解也比较好理解,就是生成toString,equals和hashcode方法,同时后者还会生成一个canEqual方法,用于判断某个对象是否是当前类的实例,生成方法时只会使用类中的非静态和非transient成员变量。
=====================================================
@Conditional @ConditionalOnBean、@ConditionalOnMissingBean (原文地址:https://blog.csdn.net/xcy1193068639/article/details/81517456)
@FeignClient 使用Spring Cloud搭建各种微服务之后,服务可以通过@FeignClient使用和发现服务场中的其他服务。(原文地址:https://blog.csdn.net/kangkanglou/article/details/76407623 )
@EnableFeignClients 通过当前service服务要调用到其他service服务的api接口时,可通过EnableFeignClients调用其他服务的api (原文地址: https://www.cnblogs.com/UniqueColor/p/7130782.html | https://blog.csdn.net/xcy1193068639/article/details/81491071)
=========================
实体类:
@Temporal() :时间类型 加不加分秒 可以自选
======================================================
FeignClient注解及参数
一、FeignClient注解
FeignClient注解被@Target(ElementType.TYPE)修饰,表示FeignClient注解的作用目标在接口上
1 2 3 4 5 |
|
声明接口之后,在代码中通过@Resource注入之后即可使用。@FeignClient标签的常用属性如下:
- name:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现
- url: url一般用于调试,可以手动指定@FeignClient调用的地址
- decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException
- configuration: Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
- fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口
- fallbackFactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码
- path: 定义当前FeignClient的统一前缀
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
在使用fallback属性时,需要使用@Component注解,保证fallback类被Spring容器扫描到,GitHubExampleConfig内容如下:
1 2 3 4 5 6 7 |
|
在使用FeignClient时,Spring会按name创建不同的ApplicationContext,通过不同的Context来隔离FeignClient的配置信息,在使用配置类时,不能把配置类放到Spring App Component scan的路径下,否则,配置类会对所有FeignClient生效.
二、Feign Client 和@RequestMapping
当前工程中有和Feign Client中一样的Endpoint时,Feign Client的类上不能用@RequestMapping注解否则,当前工程该endpoint http请求且使用accpet时会报404
Controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Feign Client
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
if @RequestMapping is used on class, when invoke http /v1/card/balance, like this :
如果 @RequestMapping注解被用在FeignClient类上,当像如下代码请求/v1/card/balance时,注意有Accept header:
1 2 3 4 |
|
那么会返回 404。
如果不包含Accept header时请求,则是OK:
1 2 |
|
或者像下面不在Feign Client上使用@RequestMapping注解,请求也是ok,无论是否包含Accept:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
三、Feign请求超时问题
Hystrix默认的超时时间是1秒,如果超过这个时间尚未响应,将会进入fallback代码。而首次请求往往会比较慢(因为Spring的懒加载机制,要实例化一些类),这个响应时间可能就大于1秒了
解决方案有三种,以feign为例。
方法一
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
该配置是让Hystrix的超时时间改为5秒
方法二
hystrix.command.default.execution.timeout.enabled: false
该配置,用于禁用Hystrix的超时时间
方法三
feign.hystrix.enabled: false
该配置,用于索性禁用feign的hystrix。该做法除非一些特殊场景,不推荐使用。
参见:http://www.itmuch.com/spring-cloud-sum-feign/