admin管理员组

文章数量:1794759

Spring系列——SpringBoot常用注解

Spring系列——SpringBoot常用注解

注解 @SpringBootApplication

此注解是Spring Boot项目的基石,创建SpringBoot项目的Application时会默认加上

@SpringBootApplication public class SpringSecurityApplication{ public static void main(Strings[] args){ SpringApplication.run(SpringSecurityApplication,args); } }

我们可以把@SpringBootApplication 看作@Configuration,@EnableAutoConfiguration,@ComponentScan 注解的集合

其中 @EnableAutoConfiguration:启用SpringBoot的自动配置机制 @ComponentScan:扫描被@Component /@Service/@Controller注解的bean,注解默认会扫描该类所在的包下所有类 @Configuration:允许在Spring上下文中注册额外的bean或导入其他配置类

Spring Bean相关 @Bean

Bean对象注册Spring IOC容器与使用bean对象是整个Spring框架的重点,其中@Bean就是一个将方法作为Spring Bean对象注册的一种方式,

package com.edu.fruit; //定义一个接口 public interface Fruit<T>{ //没有方法 } /* *定义两个子类 */ package com.edu.fruit; @Configuration public class Apple implements Fruit<Integer>{//将Apple类约束为Integer类型 } package com.edu.fruit; @Configuration public class GinSeng implements Fruit<String>{//将GinSeng 类约束为String类型 } /* *业务逻辑类 */ package com.edu.service; @Configuration public class FruitService { @Autowired private Apple apple; @Autowired private GinSeng ginseng; //定义一个产生Bean的方法 @Bean(name="getApple") public Fruit<?> getApple(){ System.out.println(apple.getClass().getName().hashCode); System.out.println(ginseng.getClass().getName().hashCode); return new Apple(); } } /* *测试类 */ @RunWith(BlockJUnit4ClassRunner.class) public class Config { public Config(){ super("classpath:spring-fruit.xml"); } @Test public void test(){ super.getBean("getApple");//这个Bean从哪来, 从上面的@Bean下面的方法中返回的是一个Apple类实例对象 } } @Autowired

@Autowired自动注入注解,最常用的一种注解将对象自动导入到类中,注解自动装配bean的类

@Component家族

@Component:通用注解,当不知道Bean在哪一层时,可以使用@Component注解标注。 @Repository: 对应持久层—Dao层的注解,用于操作数据库相关 @Service: 对应服务层的注解,用来连接Dao层做逻辑处理 @Controller:对应Spring MVC控制层,主要接收用户请求并调用service返回给前端页面

@RestController

@RestController注解是@Controller注解和@ResponseBody注解的合集,用来返回Json格式给页面(带Rest格式的就是返回的Json文本)

用@RestController注解实现前后端分离,如果是使用@Controller则项目还是太老了,返回的视图格式,在传统的SpringMVC中使用

@Scope

声明Spring Bean的作用域

@Scope("singleton") public Person personSingleton(){ return new Person(); }

Spring Bean的四种作用域:singleton,prototype,request,session

@Configuration

一般声明配置类,使用@Component或者@Configuration

@Configurantion public class AppConfig{ @Bean public TransferService transferService(){ return new TransferServiceImpl(); } } 处理常见HTTP请求类型 @RequsetMapping

@RequsetMapping是处理HTTP请求的最通用注解

@RequestMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); } @GetMapping

@GetMapping 就等价于@RequestMapping(value="/users",method =RequsetMethod.GET) 即使用@GetMapping就相当用接收GET方法了

@GetMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); } @PostMapping

@PostMapping 就等价于@RequestMapping(value="/users",method =RequsetMethod.POST) 即使用@PostMapping就相当用接收Post方法了

@PostMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); } @PutMapping

@PutMapping("/users/{userId}")等价于@RequestMapping(value = “/users/{userId}”,method = RequestMethod.PUT)

@PutMapping("/users/{userId}") public ResponseEntity<User> updateUser(@PathVariable (value ="userId")Long userId, @Valid @RequestBody UserUpdateRequest userUpdateRequest){ ... } @DeleteMapping

@DeleteMapping("/users/{userId}")等价于@RequestMapping(value ="/users/{userId}",method = RequestMethod.DELETE)

@DeleteMapping("/users/{userId}") public ResponseEntity deleteUser(@PathVariable(value = "userId) Long userId){ ... }

那么我们如何进行Put/Delete方法的获取呢 答案是通过隐藏域利用_method设定浏览器传给Controller的方法类型

<!-- 获得get --> <form action="stuManager/${stu.stuNo }.action" method="get"> <input type="submit" value="查看"> </form> <!-- 添加post --> <form action="${ctxPath}/stuManager.action" method="post"> <input type="submit" value="添加"> </form> <!-- 修改put --> <form action="${ctxPath}/stuManager.action" method="post"> <input type="hidden" name="_method" value="put"/> <input type="submit" value="修改"> </form> <!-- 删除delete --> <form action="stuManager/${stu.stuNo }.action" method="post"> <input type="hidden" name="_method" value="DELETE"> <input type="submit" value="删除"> </form> 前后端传值 @ParhVariable和@RequestParam

@PathVariable 用于获取路径参数, @RequestParam用于获取查询参数

@GetMapping("/users/{userId}/teachers") public List<Teacher> getUserRelatedTeachers(@PathVariable("userId") Long userId,@RequestParam(value = "type",required = false) String type){ ... }

其中@PathVariable是获取请求中的{userId}值, @RequestParam则是url读取请求中type的值 比如我们url请求中**/users/{123456}/teachers?type=Chinese** 则我们在Controller获取到的就是userId = 123456 , type = Chinese

另在@RequestParam中 value=“参数名” required = “true/false”(true表示参数不允许不存在,false表示参数允许不存在) defaultValue="" 设置defaultValue时默认required为false。

@RequestBody

用于读取Request请求的body部分,且Content-Type为application/json格式数据,接收到数据后会自动将数据绑定在Java对象上,系统会使用HttpMessageConverter来讲请求的body中的json字符串转换为Java对象

@PostMapping("/sing-up") public ResponseEntity signUp(@RequsetBody @Valid UserRegisterRequest userRegisterRequest){ userService.save(userRegisterRequest); return ResponseEntity.ok().build()' }

这就是典型的RequestBody在Post请求里进行传输数据

当后端Controller接收到json格式的数据后,直接就会生成Java对象映射到UserRegisterRequest类上,这样就可以直接将userRegisterRequest对象进行存储了 顺便提一句@Valid注解是用来验证数据格式是否符合要求,如果符合要求则

读取配置信

读取application.yml的注解 先给一个application.yml文件

wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油! my-profile: name: Guide哥 email: koushuangbwcx@163 library: location: 湖北武汉加油中国加油 books: - name: 天才基本法 description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消——对方考取的学校,恰是父亲当年为她放弃的那所。 - name: 时间的秩序 description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 - name: 了不起的我 description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻? @Value

上面已经给出了application.yml文件,那么我们该如何读取呢 首先是使用@Value("${property}")读取简单的配置信

@Value("${wuhan2020}") String wuhan2020;

这样就将上面的wuhan2020中的一大长串文字读取到了wuhan2020这个字符串中了

@ConfigurationProperties

我们同样可以通过@ConfigurationProperties读取配置信并与bean绑定

@Component @ConfigurationProperties(prefix = "library") class LibraryProperties{ @NotEmpty private String location; private List<Book> books; @Data @ToString static class Book{ String name; String description; } } 可以看到上面的注入方法将library中的属性按照名称分别注入到了对应的字段中。 结尾

感谢看到最后的朋友,都看到最后了,点个赞再走啊,如有不对之处还请多多指正。

本文标签: 注解常用系列springSpringBoot