Spring MVC相关注解
| Spring MVC相关注解 | 解释 |
|---|
| @Controller | 声明该类为SpringMVC中的Controller,用来处理http请求 |
| @RestController | 组合注解,@Controller + @ResponseBody.意味着,该Controller的所有方法都默认加上了@ResponseBody |
| @RequestMapping | 把htt请求映射到方法上去 |
| @PathVariable | 用于接收路径参数,比如@RequestMapping(“/hello/{name}”)申明的路径,将注解放在参数中前,即可获取该值,通常作为Restful的接口实现方法 |
| @RequestParam | 将请求参数绑定至方法参数 |
| @RequestBody | 用于读取Request请求的body部分数据 |
| @ResponseBody | 将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区 |
| @ModelAttribute | 主要作用是绑定request或是form参数到模型(Model) |
| @InitBinder | 用来设置WebDataBinder,WebDataBinder用来自动绑定前台请求参数到Model中 |
| @ExceptionHandler | 用于全局处理控制器里的异常 |
| @ControllerAdvice | 通过该注解,我们可以将对于控制器的全局配置放置在同一个位置,和@Controller对应 |
| @RestControllerAdvice | 同上和@RestController对应 |
@GetMapping("/blog/{id}")
public String blog(@PathVariable Long id,Model model) {
model.addAttribute("blog", blogService.getAndConvert(id));
return "blog";
}
@PostMapping("/search")
public String search(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
@RequestParam String query, Model model) {
model.addAttribute("page", blogService.listBlog("%"+query+"%", pageable));
model.addAttribute("query", query);
return "search";
}
@Controller
public class IndexController{}
@PostMapping("/types/{id}")
public String editPost(@Valid Type type, BindingResult result,@PathVariable Long id, RedirectAttributes attributes) {
Type type1 = typeService.getTypeByName(type.getName());
if (type1 != null) {
result.rejectValue("name","nameError","不能添加重复的分类");
}
if (result.hasErrors()) {
return "admin/types-input";
}
Type t = typeService.updateType(id,type);
if (t == null ) {
attributes.addFlashAttribute("message", "更新失败");
} else {
attributes.addFlashAttribute("message", "更新成功");
}
return "redirect:/admin/types";
}
@ControllerAdvice
public class ControllerExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception {
logger.error("Requst URL : {},Exception : {}", request.getRequestURL(),e);
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
throw e;
}
ModelAndView mv = new ModelAndView();
mv.addObject("url",request.getRequestURL());
mv.addObject("exception", e);
mv.setViewName("error/error");
return mv;
}
}
切面AOP相关注解
| 切面AOP相关注解 | 解释 |
|---|
| @Aspect | 声明一个切面,只是一个标识作用 |
| @PointCut | 声明切点,在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持 |
| @Around | 在方法执行之前与之后执行 |
| @Before | 在方法执行之前执行 |
| @After | 在方法执行之后执行 |
| @AfterReturning | 方法正常退出的时候执行 |
| @AfterThrowing | 方法有异常抛出的时候执行 |
@Aspect
@Component
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(* com.lrm.web.*.*(..))")
public void log() {}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String url = request.getRequestURL().toString();
String ip = request.getRemoteAddr();
String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
logger.info("Request : {}", requestLog);
}
@After("log()")
public void doAfter() {
}
@AfterReturning(returning = "result",pointcut = "log()")
public void doAfterRuturn(Object result) {
logger.info("Result : {}", result);
}
}
配置类相关注解
| 配置类相关注解 | 解释 |
|---|
| @SpringBootApplication | 组合注解,由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三者组成,我们一般把该注解添加在启动类上 |
| @ComponentScan | 用于指定组件的扫描路径和过滤规则 |
| @EnableAutoConfiguration | 启用自动配置,就是让@SpringBootConfiguration、@Configuration注解起作用 |
| @SpringBootConfiguration | 标注当前类是配置类 |
| @Configuration | 标注当前类是配置类 |
| @Bean | 注解在方法上,一般在@Configuration注解类下使用,把方法返回的对象添加到Spring IOC容器里面去,并且容器里面Bean的名字就是方法名 |
| @Import | 导入类,有时没有把某个类注入到IOC容器中,但在运用的时候需要获取该类对应的Bean,这个时候我们就可以使用@Import导入需要的Bean |
| @AutoConfigureAfter | 加载指定配置的类之后再加载当前类,一般和@Configuration一起出现 |
| @AutoConfigureBefore | 加载指定配置的类之前加载当前类,一般和@Configuration一起出现 |
| @AutoConfigureOrder | 指定配置类的加载顺序,一般和@Configuration一起出现 |
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin")
.excludePathPatterns("/admin/login");
}
}
参考:
https://blog.csdn.net/wuyuxing24/article/details/100803228