相关注解总结

目录

@Configuration

@Bean

@Autowired

 @Qualifier

 @Resource

@CrossOrigin

@RequestBody

@ResponseBody

@Controller

@RestController

@Transactional

@RestControllerAdvice

@ExceptionHandler(RuntimeException.class)

@Data

@Accessors(chain = true)

@Param

 @PathVariable

@TableName("user")

@TableId(type = IdType.AUTO)

@Component

@Scope("singleton")/@Scope("prototype")

@Lazy

@PostConstruct

@PreDestroy

@LoadBalanced


  1. @Configuration

    1. 将当前类标识为配置类
  2. @Bean

    1. 一般用于配置类内部,描述相关方法,用于告诉spring此方法的返回值要交给spring管理

    2. bean的名字默认为方法名,假如需要指定名字可以@Bean(“bean的名字”),最多的应用场景是整合第三方的资源-对象

    3. package com.jt.config;
      
      import com.jt.demo.User;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      @Configuration //将当前类标识为配置类
      public class SpringConfig {//xml
          /**
           *  1.xml形式
           *      <bean id="user" class="com.jt.demo.User"></bean>
           *  2.注解形式
           *     Map集合的结构 Map<方法名,方法的返回值>
           *     @Bean 将方法的返回值,交给Spring容器管理.
           */
          @Bean
          public User user(){
      
              return new User(); //相当于xml反射机制创建对象
          }
      }
      

  3. @Autowired

    1. 说明: 在对象中如果需要使用属性注入,一般使用@Autowired注解.
      功能: 可以将Spring容器中的对象,自动注入到属性中.
      注入方式:
      1. 默认按照类型注入. 如果注入的属性是接口,则自动注入实现类
      2. 按照名称注入(key). 一般不用
  4.  @Qualifier

    1. 接口多实现时使用,该注解不能单独使用,必须配合Autowired使用,根据key进行注入
    2. 案例
      package com.jt.demo;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.stereotype.Component;
      
      @Component  //将user交给Spring容器管理
      public class User {
      
          //效果: 将当前接口的实现类自动注入
          @Autowired
          @Qualifier("cat") //该注解不能单独使用,必须配合Autowired使用,根据key进行注入
          private Pet pet;  //2选1
      
          public void say(){
              //调用宠物的方法
              pet.hello();
          }
      }
      
      

      1

  5.  @Resource

    1. package com.jt.demo;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.stereotype.Component;
      
      @Component  //将user交给Spring容器管理
      public class User {
      
          //效果: 将当前接口的实现类自动注入
          @Autowired
          @Qualifier("cat") //该注解不能单独使用,必须配合Autowired使用,根据key进行注入
      //  @Resource("dog")     //功能上说:@Autowired+@Quqlifier("cat")
          private Pet pet;  //2选1
      
          public void say(){
              //调用宠物的方法
              pet.hello();
          }
      }
      
      
  6. @CrossOrigin

    1. 解决跨域问题
    2. 案例
  7. @RequestBody

    1. 主要用来接收前端传递给后端的json字符串中的数据,post请求时需要使用,否则会报空指针异常
    2. 案例
       @PutMapping("/updateUser")
          public SysResult updateUser(@RequestBody User user){
              userService.updateUser(user);
              return SysResult.success();
          }

  8. @ResponseBody

    1. 当前类中的所有方法 都返回JSON串
    2. 案例
  9. @Controller

    1. /将类交给SpringMVC管理
  10. @RestController

    1. @Controller 将类交给SpringMVC管理 + @ResponseBody 当前类中的所有方法 都返回JSON串
  11. @Transactional

    1. 声明式事务管理,将方法控制到同一事物中,报错后会回滚,不会执行
    2. spring中默认控制的是运行时异常,如果是检查异常,不会管理
    3. @Transactional(rollbackFor = SQLException.class)拦截SQL异常
    4. @Transactional(rollbackFor = Exception.class)拦截所有异常,不推荐,一般只拦截运行时异常,即采用默认注解
  12. @RestControllerAdvice

    1. 标记此类为全局处理机制,只拦截controller层
  13. @ExceptionHandler(RuntimeException.class)

    1. 拦截指定类型的异常,一般只拦截运行类
    2. 案例
      package com.jt.aop;
      
      import com.jt.vo.SysResult;
      import org.springframework.web.bind.annotation.ExceptionHandler;
      import org.springframework.web.bind.annotation.RestControllerAdvice;
      
      @RestControllerAdvice
      public class SystemException {
      
          @ExceptionHandler(RuntimeException.class)
          public SysResult exception(Exception e){
              e.printStackTrace();
              return SysResult.fail();
          }
      }
      

      1

  14. @Data

    1. 重写方法:Getter/Setter/RequiredArgsConstructor/ToString/EqualsAndHashCode

  15. @Accessors(chain = true)

    1. 重写了set方法,增加返回值,可以实现链式加载

    2. 案例1111

      package com.jt.pojo;
      
      import lombok.Data;
      import lombok.experimental.Accessors;
      
      import java.io.Serializable;
      @Data   //Getter/Setter/RequiredArgsConstructor/ToString/EqualsAndHashCode
      @Accessors(chain = true) //重写了set方法,可以直接接受User返回的对象,不用手动重写,可以实现链式加载
      public class User implements Serializable {
          private Integer id;
          private String name;
      
         /* public User setId(Integer id){
              this.id = id;
              return this; //当前对象 运行期有效
          }
      
          public User setName(String name){
              this.name = name;
              return this; //当前对象 运行期有效
          }*/
      }
      
      
    3.  lombok @Accessors用法详解
  16. @Param

    1. 将多个参数封装为一个map集合
    2. 案例
      1. package com.jt.mapper;
        
        import com.jt.pojo.Rights;
        import com.jt.pojo.User;
        import com.jt.vo.PageResult;
        import org.apache.ibatis.annotations.Param;
        
        import java.util.List;
        
        public interface UserMapper {
        
            User findUserByUP(User user);
        
            long findTotal();
        
            List<User> findUserList(@Param("start") int start, @Param("size") int size,@Param("query") String query);
        }
        

        mapper只能传单个值,所以需将多值封装为map集合

  17.  @PathVariable

    1. restFul语法:
      1. 参数与参数之间使用/分割 
      2.  需要接收的参数使用{}包裹 
      3. 参数接收时采用@PathVariable取值
    2.   /**
           * URL地址:
           *  http://localhost:8080/findUser/tomcat/18/男  get类型
           * 参数: name/age/sex
           * 返回值: 返回值获取的数据
           * restFul语法:
           *     1. 参数与参数之间使用/分割
           *     2. 需要接收的参数使用{}包裹
           *     3. 参数接收时采用@PathVariable取值
           */
          @RequestMapping("/findUser/{name}/{age}/{sex}")
          public String findUser(@PathVariable String name,
                                 @PathVariable int age,
                                 @PathVariable String sex){
      
              return name+":"+age+":"+sex;
          }
      

    3. 在使用对象接受的时候,不需要用此注解

      @GetMapping("/getItemList")
          public SysResult getItemList(PageResult pageResult){
              pageResult =itemService.getItemList(pageResult);
              return SysResult.success(pageResult);
          }
  18. @TableName("user")

    1. MyBatis注解,让对象和表名一一映射
  19. @TableId(type = IdType.AUTO)

    1. 标识主键
    2. 案例
      package com.jt.pojo;
      
      import com.baomidou.mybatisplus.annotation.IdType;
      import com.baomidou.mybatisplus.annotation.TableField;
      import com.baomidou.mybatisplus.annotation.TableId;
      import com.baomidou.mybatisplus.annotation.TableName;
      import lombok.Data;
      import lombok.experimental.Accessors;
      
      import java.util.List;
      
      /**
       * @author 刘昱江
       * 时间 2021/3/26
       */
      @Data
      @Accessors(chain = true)
      @TableName("user")
      public class ItemCat extends BasePojo {
          @TableId(type = IdType.AUTO)
          private Integer id;         //定义主键
      //    @TableField(username)     如果属性与字段一致(包含驼峰规则),则注解可以省略
          private Integer parentId;   //定义父级菜单 开启驼峰规则映射
          private String name;        //分类名称
          private Boolean status;     //分类状态 0 停用 1 正常
          private Integer level;      //商品分类等级  1 2 3
          private List<ItemCat> children;
      }
      

      1

  20. @Component

    1. 将对象交给spring容器管理
    2. 案例
      package com.jt.demo;
      
      import org.springframework.stereotype.Component;
      
      @Component //将对象交给spring容器管理 key:cat value:反射Cat对象
      public class Cat implements Pet{
      
          @Override
          public void hello() {
              System.out.println("我是喵喵喵");
          }
      }
      
      

  21.  

  22. @Scope("singleton")/@Scope("prototype")

    1. 单例/多例模式

    2. 案例

      package com.jt.config;
      
      import com.jt.demo.User;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.ComponentScan;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.context.annotation.Scope;
      
      @Configuration  //标识这是配置类
      @ComponentScan("com.jt")
      public class SpringConfig {
      
          @Bean
          @Scope("singleton")     //默认值 单例模式
          //@Scope("prototype")   //      多例模式
          public User user(){
              return new User();
          }
      }
      
      

      1

  23. @Lazy

    1. 说明: 如果Spring容器创建,对象立即创建则该加载方式为 “立即加载”, 容器启动创建
      如果Spring容器创建,对象在被使用的时候才创建, 则称为"懒加载" 用时才创建

      注解: @Lazy 添加表示改为懒加载
      测试说明: 主要测试对象中的无参构造什么时候执行!!!

    2. 案例

      package com.jt.config;
      
      import com.jt.demo.User;
      import org.springframework.context.annotation.*;
      
      @Configuration  //标识这是配置类
      @ComponentScan("com.jt")
      public class SpringConfig {
      
          @Bean
          //@Scope("singleton")    //默认值 单例模式
          //@Scope("prototype")    //  多例模式
          @Lazy                    //懒加载
          public User user(){
              return new User();
          }
      }
      
      

      1

    3. 说明: 只要对象是多例模式,则都是懒加载!, 在单例模式中控制懒加载才有效.
      规则说明:
      lazy true lazy false
      单例模式: 有效 懒加载 有效 立即加载
      多例模式: 无效 懒加载 无效 懒加载

  24. @PostConstruct

    1. 生命周期注解

      在对象创建之后立即调用
  25. @PreDestroy

    1. 对象消亡时 进行调用

    2. 案例

      package com.jt.demo;
      
      import org.springframework.stereotype.Component;
      
      import javax.annotation.PostConstruct;
      import javax.annotation.PreDestroy;
      
      @Component  //将对象交给Spring容器管理 key=person value:反射对象
      public class Person {
      
          public Person(){
              System.out.println("张三出生了,资质拉满");
          }
      
          @PostConstruct  //在对象创建之后立即调用
          public void init(){
              System.out.println("张三称为少年奇才");
          }
      
          //业务方法
          public void doWork(){
              System.out.println("迎娶美人鱼!!!");
          }
      
          @PreDestroy //对象消亡时 进行调用
          public void destory(){
              System.out.println("销毁:全世界哀悼");
          }
      }
      
      

      1

  26. @LoadBalanced

    1. 用于RestTemplate的负载均衡
    2. @Bean
      @LoadBalanced
      public RestTemplate loadBalancedRestTemplate(){
          return new RestTemplate();
      }

      主启动类

    3.  @Autowired
          private RestTemplate loadBalancedRestTemplate;
      
      //    url:http://localhost:8090/consumer/doRestEcho03
          @GetMapping("/consumer/doRestEcho03")
          public String doRestEcho03() {
              String url = String.format("http://sca-provider/provider/echo/%s", appName);
              return loadBalancedRestTemplate.getForObject(url, String.class );
      

      controller层

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值