Spring boot注解2

1. @SpringBootApplication
2. @ComponentScan
  1. is used to find beans
  2. and the corresponding injected with @Autowired annotation.
3. @Autowired
4. @Value

@value("{spring.application.name:demoservice}")
private String name

5. @ConfigurationProperties(prefix = "fame.config")

同 4 ,不同在于不用一个一个获取即写多个@Value

@ConfigurationProperties(prefix = "fame.config")
public class config {}

https://www.cnblogs.com/tanwei81/p/6814022.html

Lombok 常用注解

  1. @NoArgsConstructor :注解在类上;为类提供一个无参的构造方法
  2. @AllArgsConstructor :注解在类上;为类提供一个全参的构造方法
  3. @Synchronized : 加个同步锁
  4. @NonNull : 如果给参数加个这个注解 参数为null会抛出空指针异常
  5. @Value : 注解和@Data类似,区别在于它会把所有成员变量默认定义为private final修饰,并且不会生成set方法。
  6. @Data 注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
  7. @Builder : 被注解的类加个构造者模式
  8. @SneakyThrows : 等同于try/catch 捕获异常
  9. @Cleanup 注解用在变量前,可以保证此变量代表的资源会被自动关闭
  10. @Getter/@Setter 用在变量前
  11. @ToString/@EqualsAndHashCode
    生成toString,equals和hashcode方法,同时后者还会生成一个canEqual方法,用于判断某个对象是否是当前类的实例,生成方法时只会使用类中的非静态和非transient成员变量
    12 .@Log/@Log4j/@Slf4j \

参考博客:https://blog.csdn.net/sunsfan/article/details/53542374

Model层(JPA实体类)的常用注解

  1. @Data 是lombok的注解,自动生成Getter、setter、toString,构造函数等
  1. @Entity 注解这是个实体类,对应数据库中的一个表
  1. @Table注解表相关,指定这个类对应数据库中的表名,如果和数据库的命名方式相同,可以省略如FlowType对应表名flow_type
  1. @Id 注解主键,@GeneratedValue 表示自动生成@GeneratedValue(strategy=GenerationType.IDENTITY)指定主键的生成方式,此为自增
  1. @Column 针对一个字段,对应表中的一列,字段别名,是否允许为空,是否唯一,是否进行插入和更新(比如由MySQL自动维护)

    name 表示对应数据表中的字段名
    insertabe 表示插入是否更新
    updateable 表示update时候是否更新
    columnDefinition表示字段类型,当使用jpa自动生成表的时候比较有用
  1. @DynamicUpdate,@DynamicInsert 注解可以动态的生成insert、update 语句,默认会生成全部的update
  2. @Transient 标识该字段并非数据库字段映射
  3. @JsonProperty 定义 Spring JSON 别名,
    @JsonIgnore 定义 JSON 时忽略该字段,
    @JsonFormat 定义 JSON 时进行格式化操作
  4. @PrePersist 表示持久化之前执行
  5. @PreUpdate 表示Update操作之前执行
  6. @Where当执行查询语句时,会附带这个条件
    12 .@MappedSuperclass 表示一个这是一个父类,不会被当成一个实体类。在这里定义一些表中的通用字段。然后其他实体类继承这个类就可以了,避免写重复代码。

Controller层常用注解

  1. @Controller处理http请求,用来响应页面
    必须配合模板来使用
    如:Thymeleaf(官网使用)
    Groovy
    return "hello" // 返回hello模板,如果是@RestController就返回hello字串
    1.1 @PathVariable 获取url中的数据 ,变量前修饰
    1.2 @RequestParam 获取请求参数的值 变量前修饰
    1.3 GetMapping (是@RequestMapping(method = RequestMethod.GET)的缩写)组合注解 方法上
    1.4 PostMapping 组合注解,方法上
    1.5 DeleteMapping 组合注解,方法上 \
  1. @RestController
    Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。
    @ResponseBody和@Controller的组合注解
  1. @RequestMapping 配置url映射
    可以作用在控制器某个方法上,也可以作用在此控制器类上
    1 在类级别上添加@RestMapping注解: 会应用到控制器的所有方法上(相当于设置了base_url)
    2 在方法上时,对类级别的映射进行扩展 base_url/path
  1. @ControllerAdvice
  1. 接口类项目开发,为了便于后期查找问题,一般会使用拦截器或者过滤器记录每个接口请求的参数与响应值记录
    @ControllerAdvice 捕获Controller层抛出的异常,如添加@response返回信息为Json格式
    @RestControllerAdvice 相当于 @ControllerAdvice 与 @Response结合体 \
  1. @Controller是Springmvc controller增强器,是组件注解,使其实现类能够被classpath扫面自动发现,遵循MVC命令空间啥的是默认自动开启的
  2. @ControllerAdvice以下的注解方法会被应用到控制器类层次的所有@RequestMapping上:
  1. ModelAttribute:暴露@RequestMapping 方法返回值为模型数据
    放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。
  2. @InitBinder 用于定义@RequestMapping 方法参数绑定,即应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
    @InitBinder
    public void initBinder(WebDataBinder binder) {}
   3. ResponseBodyAdvice: 用于@ResponseBody返回值增加处理(重写某些方法)
   4. @ModelAttribute
      在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取 \
            /**
               * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
               * @param model
               */
              @ModelAttribute
              public void addAttributes(Model model) {
                  model.addAttribute("author", "Magical Sam");
              }
              
              
              @RequestMapping("/home")
              public String home(ModelMap modelMap) {
                  System.out.println(modelMap.get("author"));
              }
          
              //或者 通过@ModelAttribute获取
          
              @RequestMapping("/home")
              public String home(@ModelAttribute("author") String author) {
                  System.out.println(author);
              }
      
   5. @ExceptionHandler
      1. SpringBoot提供了一个默认映射:/error,当处理中抛出异常之后,会转到请求中处理,并且该请求有一个全局的错误页面来展示异常 \
      2. @ExceptionHandler用来定义函数针对的异常类型 \
         1. Exception对象(@ExceptionHandler(value = Exception.class))和请求url出错时映射到error.html中
         2. Exception对象和请求url出错时返回json对象
      3. 只能针对于Controller层的异常,意思是只能捕获到Controller层的异常,在service层或者其他层面的异常都不能捕获,Controller层做了catch处理就不能捕获了
      
4. ControllerAdvice初始化:
   Spring mvc 启动时调用RequestMappingHandlerAdapter类的initControllerAdviceCache()方法进行初始化
5. 是spring4.1的新特性,其作用是在响应体写出之前做一些处理;比如,修改返回值、加密等

    @ControllerAdvice
    public class ResponseAdvisor implements ResponseBodyAdvice {}

  1. Springcloud配置服务器
    https://www.cnblogs.com/hellxz/p/9306507.html

4. Interceptor

Before sending the request to the controller

Before sending the response to the client \

比如可以在此过程中对header进行添加操作 拦截器 登录 。。。 \

实现:\

  1. @Component \
  1. implement the HandlerInterceptor interface \
  1. registering this Interceptor with InterceptorRegistry by using WebMvcConfigureAdapter

@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

return true;
}
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception exception) throws Exception {}

-----注册-------
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
@Autowired
ProductServiceInterceptor productServiceInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(productServiceInterceptor);
}
}


Mybatis

简化JDBC代码,使代码保持简洁 \

学习博客: https://www.cnblogs.com/wlsblog/p/7879263.html

1. XML文件配置及映射文件
2. Java Api

MyBatis的主要Java接口就是SqlSession \

  1. SqlSession由SqlSessionFactory创建(由Sql SessionFactoryBuilder创建)-XML创建,代码创建等 \
1.  配置configuration实例,然后传给builder()方法来创建SqlSessionFactory \
    
    
2.  SqlSessionFactory 有6个方法来创建SqlSession实例,有几个考虑点:\
    
    
    
    Transaction: \
    
    
    
    Connection: \
    
    
    
    Execution: \
    
    
    
    通过重载openSession()方法签名 \
    
    
    
    语句执行方法 \
    
    
3.  映射器类 \
    
    
    1.  大部分基于XML的映射器元素都提供了相应的注解配置项,然而基于注解配置还不能完全支持XML的一些元素
        
        
    2.  映射器接口不需要去实现任何借口或扩展任何类,只要方法前面可以被用来唯一标识对应的映射语句就OK了 \
        
        
    3.  映射器注解: \
        
        
    @Insert(Statement,x)
    @Options(useGenerateKeys=true,keyProperty="") //让数据库产生auto_increment(自增长的列),然后将生成的值设置到输入参数对象的属性中
    int insertStudents(Student student);
    ​
    @SelectKey(statement="",keyProperty="",resultType=xx,before=true) : 为任意Sql语句来指定主键值,作为主键列的值,before 优先级
4. 结果映射:\ 将查询结果通过别名或者是@Result主键与JavaBean属性映射起来 @Select("") @Results( { @Result(id=true,column="",property="") @Result(column="",property="") }) @Results 注解和映射器XML配置文件元素对应 ​ @Select("") @ResultMap -->找到对应的配置文件,把select查询结果映射到配置文件 5. 一对一映射: @One 注解来使用嵌套select语句加载一对一关联查询语句,接受的参数为字段列的一个 6. 一对多映射: @Many 该方法放回一个List对象,接受的参数为字段列所有 7. 动态SQL 根据输入条件动态地创建SQL语句,SQL语句使用拼接形式非常不友好 ,\ org.apache.ibatis.jdbc.SQL工具类使用

Spring boot -Admin Server

对 Actuator的提升,因为他有点difficult。如果有n个applications,每个application都要有独立的actuator end point

Amind Server is an application used to manage and monitor your MicroService application

  1. 添加依赖


de.codecentric
spring-boot-admin-server
1.5.5


de.codecentric
spring-boot-admin-server-ui
1.5.5

  1. 入口类添加@EnableAdminServer

Spring Boot - EurekaServer

Eureka Server is an application that holds the information about all client-service application

  1. Every Micro service will register into Eureka Server
  1. Eureka server knows all the client applications 运行的端口和IP
  1. Discovery Server
  1. 默认地,Eureka Server register itself into the discovery

使用:

  1. 依赖导入

  1. org.springframework.cloud
    spring-cloud-starter-eureka-server
  1. @EnableEurekaServer (入口处) - 标志这个application成为Eureka Server
  1. Application.yml 文件配置

Spring Boot Service Registration with Eureka

How to register the Spring Boot Micro service application into the Eureka Server.

  1. 确保Eureka Server 运行
  1. 依赖导入

org.springframework.cloud
 spring-cloud-starter-eureka
  1. @EnableEurekaClient (入口处) - 标志这个application成为Eureka Client
  1. application.yml配置文件

eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka
instance:
preferIpAddress: true
spring:
application:
name: eurekaclient

  1. @Service

具体业务层服务service的实现,和controller层分离

  1. 跨域的实现 WebMvcConfigurer

@CrossOrigin(origins = "http://localhost:8080") //RequestMapping一起,控制层某个服务
全局跨域的实现

@Bean \\
public WebMvcConfigurer corsConfigurer() {
   return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/products").allowedOrigins("http://localhost:9000");
      }    
   };
}
@EnableScheduling

入口类添加 定时任务
@Schedule(cron="",fixRate) 具体实现

kafka

https://blog.csdn.net/lingbo229/article/details/80761778

https://www.cnblogs.com/scode2/p/8984937.html

你可能感兴趣的:(Spring boot注解2)