SpringBoot常用注解和原理简介说明

书欣 SpringBoot 发布时间:2022-08-30 22:16:25 阅读数:4266 1
下文笔者讲述SpringBoot常见注解的简介说明,如下所示

启动注解@SpringBootApplication

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.Runtime)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    // ... 此处省略源码
}

注意事项:
   1.@SpringBootApplication是一个复合注解
    包含@SpringBootConfiguration
     @EnableAutoConfiguration
     @ComponentScan这三个注解
   2.@SpringBootConfiguration注解
     继承@Configuration注解
     主要用于加载配置文件
   3.@EnableAutoConfiguration注解
      开启自动配置功能
	  可将符合条件的@Configuration配置
	  加载到IoC容器
    4.@ComponentScan注解:
	    主要用于组件扫描和自动装配
        自动扫描并加载符合条件的组件或bean定义
        最终将这些bean定义加载到容器中
      可使用basePackages等属性指定@ComponentScan自动扫描的范围
      当不指定此属性值时
       则默认Spring框架实现从声明@ComponentScan所在类的package进行扫描
       当我们不指定属性值时,则SpringBoot的启动类最好放在root package下

Controller相关注解

@Controller
   控制器,处理http请求
@RestController 复合注解

@RestController源码

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     * @since 4.0.1
     */
    @AliasFor(annotation = Controller.class)
    String value() default "";
}
从以上的源码中,我们可以得出
@RestController注解相当于
   @ResponseBody+@Controller合在一起的功能

@RestController的功能:
    将方法返回的对象采用json的方式返回

@RequestBody

使用HttpMessageConverter 
  读取Request Body并反序列化为Object(泛指)对象

@RequestMapping

@RequestMapping是Spring Web应用程序中最常被用到的注解之一
  这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上

@GetMapping

@GetMapping:
   用于将HTTP get请求映射到特定处理程序的方法注解

注解简写:
   @RequestMapping(value = "/test",method = RequestMethod.GET)
    等同于@GetMapping(value = "/test")

GetMapping源码

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {
//...
}
是@RequestMapping(method = RequestMethod.GET)的缩写

@PostMapping

@PostMapping用于将HTTP post请求映射到特定处理程序的方法注解

@PostMapping源码

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {
    //...
}
 
 等同于@RequestMapping(method = RequestMethod.POST)的缩写

取请求参数值

@PathVariable:获取url中的数据

@Controller
@RequestMapping("/User")
public class TestController {

    @RequestMapping("/getUser/{uid}")
    public String getUser(@PathVariable("uid")Integer id, Model model) {
        System.out.println("id:"+id);
        return "user";
    }
}
示例url:http://localhost:8080/User/getUser/888

@RequestParam:获取请求参数的值

@Controller
@RequestMapping("/User")
public class HelloWorldController {

    @RequestMapping("/getUser")
    public String getUser(@RequestParam("uid")Integer id, Model model) {
        System.out.println("id:"+id);
        return "user";
    }
}

示例url:http://localhost:8080/User/getUser?uid=888
@RequestHeader 把Request请求header部分的值绑定到方法的参数上
@CookieValue 把Request header中关于cookie的值绑定到方法的参数上

注入bean相关

@Repository
DAO层注解
  DAO层中接口继承JpaRepository
  需要在build.gradle中引入相关jpa的一个jar自动加载。

Repository注解源码

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    @AliasFor(annotation = Component.class)
    String value() default "";

}

@Service注解源码

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    @AliasFor(annotation = Component.class)
    String value() default "";
}
@Service注解注意事项:
   @Service是@Component注解的一个特例,作用在类上
   @Service注解作用域默认为单例
    使用注解配置和类路径扫描时,被@Service注解标注的类会被Spring扫描并注册为Bean
   @Service用于标注服务层组件,表示定义一个bean
   @Service使用时没有传参数,Bean名称默认为当前类的类名,首字母小写
   @Service(“serviceBeanId”)或@Service(value=”serviceBeanId”)使用时传参数
     使用value作为Bean名字

@Scope作用域注解

@Scope作用在类上和方法上
  用来配置spring bean作用域
  标识bean作用域

@Scope源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

    /**
     * Alias for {@link #scopeName}.
     * @see #scopeName
     */
    @AliasFor("scopeName")
    String value() default "";

    @AliasFor("value")
    String scopeName() default "";

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}
属性介绍
value
    singleton   表示该bean是单例的。(默认)
    prototype   表示该bean是多例的,即每次使用该bean时都会新建一个对象。
    request     在一次http请求中,一个bean对应一个实例。
    session     在一个httpSession中,一个bean对应一个实例。

proxyMode
    DEFAULT         不使用代理。(默认)
    NO              不使用代理,等价于DEFAULT。
    INTERFACES      使用基于接口的代理(jdk dynamic proxy)。
    TARGET_CLASS    使用基于类的代理(cglib)。

@Entity实体类注解

@Table(name =“数据库表名”),这个注解也注释在实体类上,对应数据库中相应的表。
@Id、@Column注解用于标注实体类中的字段,pk字段标注为@Id,其余@Column。

@Bean产生一个bean的方法

@Bean明确地指示了一种方法
  产生一个bean的方法
  交给Spring容器管理
  支持别名@Bean(“xx-name”)

@Autowired 自动导入

@Autowired注解作用在构造函数、方法、方法参数、类字段以及注解上
@Autowired注解可以实现Bean的自动注入

@Component

可将普通pojo实例化到spring容器中

导入配置文件

@PropertySource注解
1.引入单个properties文件:
   @PropertySource(value = {"classpath : xxxx/xxx.properties"})

2.引入多个properties文件:
   @PropertySource(value = {"classpath : xxxx/xxx.properties","classpath : xxxx.properties"})

3.@ImportResource导入xml配置文件
  可以额外分为两种模式 相对路径classpath,绝对路径(真实路径)file
 注意事项:
   单文件可以不写value或locations
    value和locations都可用
 例:
   引入单个xml配置文件:@ImportSource(“classpath : xxx/xxxx.xml”)
   引入多个xml配置文件:@ImportSource(locations={“classpath : xxxx.xml” , “classpath : yyyy.xml”})

绝对路径(file)
   引入单个xml配置文件:@ImportSource(locations= {“file : d:/hellxz/dubbo.xml”})
   引入多个xml配置文件:@ImportSource(locations= {“file : d:/hellxz/application.xml” , “file : d:/hellxz/dubbo.xml”})

取值

可使用@Value注解
  获取配置文件中的值
例:
@Value("${properties中的键}")
private String xxx;

@Import注解简介

   @Import:用于导入额外的配置信息
     用来导入配置类
     可以导入带有@Configuration注解的配置类或
	  实现ImportSelector/ImportBeanDefinitionRegistrar
@SpringBootApplication
@Import({MessageConfig.class})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

事务注解 @Transactional

在Spring中
  事务有两种实现方式
   编程式事务管理和声明式事务管理

编程式事务管理:
   编程式事务管理使用TransactionTemplate或
   直接使用底层的PlatformTransactionManager
  编程式事务管理,笔者建议使用TransactionTemplate

声明式事务管理:
  建立在AOP之上的
  其本质是对方法前后进行拦截
   然后在目标方法开始之前创建或加入一个事务
   在执行完目标方法之后根据执行情况提交或者回滚事务
    通过@Transactional就可以进行事务操作,更快捷而且简单。推荐使用

全局异常处理

@ControllerAdvice 统一处理异常
@ControllerAdvice 注解定义全局异常处理类
例:
@ControllerAdvice
public class GlobalExceptionHandler {
}

@ExceptionHandler:
   注解声明异常处理方法
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202208/4284.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者