SpringBoot笔记


Java黑马B站学成在线项目笔记

Spring Boot接口开发常用注解

启动注解@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 {

}

由源码可以发现:@SpringBootApplication是一个复合注解,包含了@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan

@SpringBootConfiguration 注解,继承@Configuration注解,主要用于加载配置文件

@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类, 并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。

@EnableAutoConfiguration 注解,开启自动配置功能

@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持,@EnableAutoConfiguration可以智能的自动配置功效才得以大功告成

@ComponentScan 注解,主要用于组件扫描和自动装配

@ComponentScan的功能其实就是自动扫描并加载符合条件的组件或bean定义,最终将这些bean定义加载到容器中。我们可以通过basePackages等属性指定@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现从声明@ComponentScan所在类的package进行扫描,默认情况下是不指定的,所以SpringBoot的启动类最好放在root package下。

Controller注解

  • @Controller标记此类是一个控制器,可以返回视图解析器指定的html页面,通过@ResponseBody可以将结果返回json、xml数据

  • RestController相当于@Controller@ResponseBody,实现rest接口开发。返回json数据,不能返回html页面

  • @RequestMapping定义接口地址,可在标记在类上也可以标记在方法上,支持http的get、post、put等接口

  • @GetMapping定义get接口,只能标记在方法上,用于查询接口定义,等价于@RequestMapping(method = RequestMethod.GET)

  • @PostMapping定义post接口,只能标记在方法上,用于添加记录、复杂条件查询接口,等价于@RequestMapping(method = RequestMethod.POST)

  • @PutMapping定义put接口,只能标记在方法上,用于修改接口定义,等价于@RequestMapping(method = RequestMethod.PUT)

  • @DeleteMapping定义delete接口,只能标记在方法上,用于删除接口定义,等价于@RequestMapping(method = RequestMethod.DELETE)

  • @ApiOperationswagger注解,对接口方法进行说明

  • @Apiswagger注解,对接口类进行说明

参数注解

  • @RequestBody定义在方法参数上,用于将json串转成java对象

  • @PathVarible接收请求路径url中的占位符的值

            @RequestMapping("/getContent/{uid}")
        public Content getContent(@PathVariable("cid")Integer id) {
            System.out.println("cid:"+id);
            return null;
        }
  • @RequestParam获取请求参数的值

            @RequestMapping("/getContent")
        public Content getContent(@RequestParam("cid")Integer id) {
            System.out.println("cid:"+id);
            return null;
        }

Bean注解

  • @ReposiforyDAO层注解
  • @Service 是@Component注解的一个特例,作用在类
  • @Scope 作用在类和方法上,用来配置spring bean的作用域
  • @Component将普通pojo实例化到spring容器
  • @Autowired 基于类型注入,主要用于构造函数、方法、方法参数、类字段。用于实现Bean的自动注入
  • @Resource基于名称注入,如果基于名称注入失败则转为基于类型注入

文章作者: youzg
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 youzg !
评论
  目录