Day 09 - Spring Boot 常用注释(下)

Spring Boot 的注释是用来告知Spring 框架,底下的程序码代表的意思,并且可以设定相关参数,用来减少重复的程序码。

Controller 常用注释

  1. @Controller : 宣告这是SpringMVC Controller 物件,用於标记控制器层。
  2. @RestController : 作用相当於@ResponseBody 加上@Controller,用於回传JSON、XML 等资料,但不能回传HTML 页面。
  3. @RequestMapping : 标示请求的位址,若用在类别上表示所有回应请求的方法都是以该路径作为父路径,而它还有六个重要的参数。
    1. value : 指定请求位址。
    2. method : 指定请求的类型,如GET、POST、PUT、DELETE 等。
    3. consumes : 指定处理请求提交的内容类型(Content-Type)。
    4. produces : 指定返回的内容类型,只有当请求头中的Accept 类型中包含该指定类型才回传。
    5. headers : 指定请求中必须包含某些header 值。
    6. params : 指定请求中必须包含某些参数值。
    @Controller
    @RequestMapping(value = "/father")
    public class IndexController {
    	// 请求路径为"/",请求方法为GET
    	@RequestMapping(value = "/test1", 
    									method = RequestMethod.GET)
    	public String test1() {
    		// 忽略
    	}
    
    	// 请求路径为"/"或是"/test2",请求方法可为GET 或POST
    	@RequestMapping(value = {"/", "/test2"}, 
    									method = {RequestMethod.GET, RequestMethod.POST})
    	public String test2() {
    		// 忽略
    	}
    
    	// 请求提交内容类型为application/JSON,返回内容类型为application/JSON
    	@RequestMapping(value = "/test3",
    									method = ReuqestMethod.POST,
    									consumes = {"application/JSON"},
    									produces = {"application/JSON"})
    	public String test3() {
    		// 忽略
    	}
    
    	// 指定header 元素值包含content-type=text/plain
    	@RequestMapping(value = "/test4",
    									method = RequestMethod.GET,
    									headers = {"content-type=text/plain"})
    	public String test4() {
    		// 忽略
    	}
    
    	// 指定请求参数值为10,也就是路径/test5?id=10 才进行处理
    	@RequestMapping(value = "/test5",
    									method = RequestMethod.GET,
    									params = {"id=10"})
    	public String test5() {
    		// 忽略
    	}
    }
    
  4. @RequestBody : 常用来处理application/json、application/xml 等Content-Type 类型的资料,表示HTTP 讯息是JSON/XML 格式,需将其转化为指定类型参数。
  5. @ResponseBody : 透过适当的HttpMessageConverter 将控制器中方法传回的物件转为指定格式(JSON/XML)後,写入Response 物件的Body 资料区。
  6. @ModelAttribute : 将请求资讯封装为指定物件。
    @RequestMapping(value = "/test6",
    								method = RequestMethod.GET,
    public String test6(
    				@ModelAttribute Member member) {
    	// 将请求参数封装为Member 物件
    }
    
  7. @SessionAttribute : 用於注入Session 物件。
    @RequestMapping(value = "/test7",
    								method = RequestMethod.GET,
    public String test7(
    				@SessionAttribute("SESSION_NAME") Member member) {
    	// 将Session 名称为SESSION_NAME 的Session 物件注入到Member 物件
    }
    
  8. @RequestParam : 将传入变数的值绑定到与@RequestParam 注释指定名称相同的参数上,若变数为非必须可以设定required = false。
    @RequestMapping(value = "/test8",
    								method = RequestMethod.GET,
    public String test8(
    				@RequestParam(value = "param1") String param1, 
    				@RequestParam(value = "param2", required = false) String param2) {
    	// 传入变数名称为param1 的值绑定到param1
    	// 传入变数名称为param2 的值绑定到param2,但param2 变数可以不存在
    }
    
  9. @PathVariable : 透过URL 中的范本变数{PATH_PARAM} 绑定到与@PathVariable 注释指定名称相同的参数上,@RequestMapping 可以定义动态的路径。
    @RequestMapping(value = "/test9/{PATH_PARAM}",
    								method = RequestMethod.GET,
    public String test9(
    				@PathVariable("PATH_PARAM") String path_param) {
    	// 假设请求路径为/test9/param,path_param 的值就为param
    }
    

Service 常用注释

  1. @Service : 宣告这是业务处理类别(实现非介面类别),用於标记业务处理层。

Dao 常用注释

  1. @Repository : 宣告这是资料库存取类别(实现非介面类别),用於标记资料存取层。

Bean 相关注释

  1. @Component : 代表该类别是Spring 管理的,常用在无法使用@Service、@Repository 描述的Spring 管理类别上,相当於通用的注释。
  2. @ComponentScan : 用来扫描元件,自动发现和装配一些Bean,根据定义的扫描路径把符合扫描规则的类别装配到Spring 容器中,预设会从宣告@ComponentScan 所在类别的套件进行扫描。
  3. @Configuration : 宣告这是设定类别,常与@Bean 配合使用。
  4. @Bean : 宣告该方法的回传结果是一个由Spring 容器管理的Bean,Bean 名称可由属性name 定义,若未定义则预设为方法名称。
    @Configuration
    public class UserConfig {
    	@Bean(name = "AdminBean")
    	public User admin() {
    		User user = new User();
    		user.setId("1");
    		user.setName("Administrator");
    
    		return user;
    	}
    
    	@Bean(name = "UserBean")
    	public User user() {
    		User user = new User();
    		user.setId("2");
    		user.setName("User");
    
    		return user;
    	}
    }
    
  5. @Resource : 用来装配Bean,预设按byName 自动注入。
  6. @Autowired : 用来装配Bean,预设按byType 自动注入。
  7. @Qualifier : 指定Bean 的名称,和@Autowired 搭配使用,当一个Type 有多个Bean 时,@Autowired 搭配@Qualifier 才能取得正确的Bean。
    // AdminBean 为Bean 的名称
    @Autowired
    @Qualifier("AdminBean")
    private User admin;
    
  8. @Value : 用於取得设定档中的值。
    // VALUE_NAME 为设定档中的名称
    @Value("${VALUE_NAME}")
    private String value_name;
    

例外处理相关注释

  1. @ControllerAdvice : 与@RestControllerAdvice 相同,用於对例外统一处理,预设对所有Controller 生效,也可按照注释、套件名称或是类型限定生效范围。
  2. @ExceptionHandler : 用在方法上,表示遇到这个例外就执行该方法。
// 限定注释为RestController 生效
// @ControllerAdvice(annotations = RestController.class)
// 限定com.example.iThomeIronMan.controller Package 下生效
// @ControllerAdvice("com.example.iThomeIronMan.controller")
// 限定Controller1 与Controller2 生效
// @ControllerAdvice(assignableTypes = {Controller1.class, Controller2.class})
@ControllerAdvice
public class ExceptionHandler {
	// 处理NullPointerException 例外
	@ExceptionHandler(NullPointerException.class)
	public String NullPointerExceptionHandler() {
		// 忽略
	}

	// 处理ArithmeticException 和ArrayIndexOutOfBoundsException 例外
	@ExceptionHandler({ArithmeticException.class, ArrayIndexOutOfBoundsException.class})
	public String NullPointerExceptionHandler() {
		// 忽略
	}
}

排程相关注释

  1. @EnableScheduling : 启用排程工作。
  2. @Scheduled : 支援多种类型的排程工作,包含cron、fixedDelay 、fixedRate 等。
// 表示该方法为每天中午12 点执行
@Scheduled(cron = "0 0 12 * * ?")
public void task1() {
	// 忽略
}

// 表示该方法执行完毕後5000ms 再次执行
@Scheduled(fixedDelay = 5000)
public void task2() {
	// 忽略
}

// 表示该方法开始执行後5000ms 再次执行
@Scheduled(fixedRate = 5000)
public void task3() {
	// 忽略	
}

AOP 相关注释

  1. @Aspec : 用於标记切面类别。
  2. @Pointcut : 标记切入点。
  3. @Before : 在切入点开始处执行。
  4. @After : 在切入点结尾处执行。
  5. @AfterReturning : 在切入点传回(return)内容後执行,用於对传回内容进行一些加工处理。
  6. @Around : 在切入点前後执行,并可控制何时执行切入点本身的内容。
  7. @AfterThrowing : 当切入点抛出例外後执行。
// 将当前类别标示为Spring 容器管理的类别
@Component
@Aspec
public class LogAspect {
	@Pointcut("execution(* com.example.iThomeIronMan.controller..*(..))")
	public void pointcut() {
	}

	@Before("pointcut()")
	public void before(JoinPoint joinPoint) {
		// 忽略
	}

	@After("pointcut()")
	public void after(JoinPoint joinPoint) {
		// 忽略
	}

	@AfterReturning(pointcut = "pointcut()", returning = "result")
	public void afterReturning(JoinPoint joinPoint, Object result) {
		// 忽略
	}

	@Around("pointcut()")
	public void around(ProceedingJoinPoint joinPoint) {
		// 忽略
	}

	@AfterThrowing(pointcut = "pointcut()", throwing = "throwable")
	public void afterThrowing(JoinPoint joinPoint, Throwable throwable) {
		// 忽略
	}
}

其他常用注释

  1. @EnableAsync : 用来开启非同步注释功能。
  2. @SpringBootTest : Spring Boot 用於测试的注释,指定入口类别或测试环境等。
  3. @Test : 标示为测试方法。
  4. @Transactional : 基於动态代理的机制,提供了一种透明的事物管理机制,只要标记在方法上,抛出异常就rollback,没有发生异常就commit,自动提交事物。
    @Transactional(rollbackFor = Exception.class)
    public void method() {
    	// 忽略
    }
    

参考网站

Spring @Transactional注解浅谈
Spring Boot Scheduling Tasks 定时任务排程器及Cron表示式 - IT Skills 波林 Polin WEI - 资讯工作者的技术手札
简易介绍,使用spring @Scheduled 注解执行定时任务! @ 瑞先生 :: 痞客邦 ::


<<:  [Day23] Tableau 轻松学 - TabPy 安装与连线

>>:  未来世界的树 - DOM Tree

Python Flask 架站笔记 第1天 基本介绍

一年多前有去外面上课(怕干扰课程招生我就不说是哪一门课程了),因为工作主要内容是数据分析,这方面的开...

第 55 天 - 帐号管理 - 新增,简单查看

今天进度 : 鸟哥的 Linux 私房菜 -- 第 10 堂课:使用者管理与 ACL 权限设定 尝试...

用自己方式存在的工程师 - TonyQ [中]

Bernard:有人说,当一个工程师,就要不断的学习。但现在可以学、要学的东西这麽多,单是前端框架就...

ISO 27001 资讯安全管理系统 【解析】(二十三)

识别情景 结合前面所有的资讯,我们可以将威胁利用弱点损害资产的机密性、可用性及完整性的情景重建与识...

Day5-就差那麽那麽一点点!!!(指尖宇宙系列

混乱的周一转了一大圈!那股慌张感涌上心头! 就是你!就是因为没有见到你! 差点断更阿! ------...