SpringBoot注解总结

SpringBoot注解总结

@Autowired 和@Resource 区别

@Resource 通过类型注入对象

@Autowired 通过名字注入对象

// 正确
@Resource 
private Person p;
    
// 错误
@Autowired
private Person p; 
    
// 正确
@Autowired
@Qualifier("person")
private Person p;
  
// 正确
@Autowired
private Person person;

@Test 和 @Test的区别

org.junit.jupiter.api.Test 和org.junit.Test的区别

查阅了下资料,原理是:

在Spring Boot 2.2.X以后使用import org.junit.jupiter.api.Test Junit5

在Spring Boot 2.2.x之前使用import org.junit.Test Junit4

导致的问题是:如果在Spring Boot 2.2.X以后使用org.junit.Test Junit4 ,则测试类中无法注入,运行时提示Null,如下代码。

@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
错误信息如下:
java.lang.NullPointerException
at com.xxx.docsearch.SpringDataEsTest.create(SpringDataEsTest.java:21)

Spring

@Component (@Repository @Service @Controller)
@Scope 作用域:单例和多例
@PostConstruct bean初始化时执行
@PreDestroy bean销毁时执行
@Bean 加载第三方资源
@Value 设置对应属性的值
@Autowired 自动注入引用类型的属性
@Qualifier 指定引用类型的bean的Id
@Primary 优先装配
@Order 指定bean的加载顺序,值越小越加载
@PropertySource 加载properties文件
@Configuration 标识spring的配置类
@ComponentScan 指定扫描的包名
@Import 导入配置类
@DependsOn 依赖指定的bean
@Lazy 延迟加载
@Aspect 通知类(AOP)
@Pointcut 切入点(AOP)
@Before 前置通知(AOP)
@After 后置通知(AOP)
@AfterReturning 返回后通知(AOP)
@AfterThrowing 抛出异常通知(AOP)
@Around 环绕通知(AOP)
@EnableAspectJAutoProxy 启动AOP注解驱动(AOP)
@RunWith 设定spring专用的类加载器(JUnit)
@ContextConfiguration spring上下文对应的配置(JUnit)
@Transactional 开启事务
@EnableTransactionManagement 启用事务驱动

Spring mvc

@EnableWebMvc 启用WebMvc
@RequestMapping 指定访问URL
@RequestParam 绑定请求参数与对应处理方法形参间的关系
@DateTimeFormat 指定日期转换格式
@RequestBody 指定请求参数为正文
@ResponseBody 指定返回内容为正文
@CrossOrigin 开启跨域访问支持
@ControllerAdvice 标识为异常处理类
@ExceptionHandler 方法上:指定处理的异常类型
@RestControllerAdvice = @ControllerAdvice + @ResponseBody
@GetMapping 查询操作
@PostMapping 保存、新增操作
@PutMapping 修改操作
@DeleteMapping 删除操作
    @RestController = @Controller + @Response
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容