【持续记录】SpringBoot常用注解

Spring内置注解

启动类

@SpringBootApplication

Spring Boot的项目一般都会有XxxApplication的入口类,入口类中会有main方法,这是一个标准的Java应用程序的入口方法。
这个入口类都会有@SpringBootApplication注解,它让Spring Boot自动给程序进行必要的配置,该注解是SpringBoot特有的。
这个配置等同于以下几个注解之和:
@SpringBootConfiguration:表示Application作为配置文件存在
@EnableAutoConfiguration:表示启用SpringBoot内置的自动配置功能
@ComponentScan : 扫描bean,路径为Application类所在package以及package下的子路径,在spring boot中bean都放置在该路径以及子路径下。

表现层

@Controller等。

@RestController
public class TestController {
    
    
    @RequestMapping("/test")
    public String test(){
    
    
        return "test!";
    }
}

@RestController 和 @ RequestMapping 是 SpringMVC 的注解,不是 SpringBoot 特有的注解。
(1)@RestController
用于处理HTTP请求,@RestController= @Controller +@ResponseBody
(2)@ResponseBody
将java对象转为json格式的数据。
@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。
注意:在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用,如AJAX。
(3)@RequestMapping
用于配置url映射
@GetMapping组合注解相当于 @RequestMapping(method = RequestMethod.GET)
@PostMapping 组合注解相当于 @RequestMapping(method = RequestMethod.POST)
(4)@RequestParam
将请求参数绑定到你控制器的方法参数上,是springmvc中接收普通参数的注解。
请求中的参数名和处理器中的形参名不一致时用 @RequestParam。
语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
value:参数名
required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值。

@GetMapping("/add")
public void addUser(@RequestParam("name")String name){
    
    

}

业务层

@Service等。

持久层

@Repository等。
@Mapper

任意层

(1)@Component
@Component, @Service, @Controller, @Repository是Spring注解,注解后可以被Spring框架所扫描并注入到Spring容器来进行管理。
@Component是通用注解,其他三个注解是这个注解的拓展,并且具有了特定的功能。
(2)读取配置文件
@Value:注入Spring boot application.properties配置的属性的值。
(3)生成Bean
@Autowired:自动导入依赖的bean。
@Resource:@Autowired与@Resource都可以用来装配bean,都可以写在字段上或写在setter方法上。

测试

比如在IDEA开发工具的test模块对代码进行测试,此时在类上使用@RunWith(SpringRunner.class)和@SpringBootTest注解,方法上使用@Test注解。
注意:
(1)测试类的所在目录名称和启动类所在目录名称要一致,否则报错:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

(2)在类上单独使用@SpringBootTest注解也可以运行测试用例,但如果在测试类中使用@Autowired等注解生成bean,必须加@RunWith(SpringRunner.class)注解。

@RunWith(SpringRunner.class)
@SpringBootTest
public class EsTest {
    
    
    @Test
    void contextLoads() {
    
    
    }
}

(3)对于@Test注解,它来自于org.junit.Test,可能会使用org.junit.jupiter.api.Test;此时报错:

报错:org.junit.runners.model.InvalidTestClassError: Invalid test class

Guess you like

Origin blog.csdn.net/JWbonze/article/details/108781475