springboot 注解

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对应
//th:href="@{/blog/{id}(id=${blog.id})}
@GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model) {
        model.addAttribute("blog", blogService.getAndConvert(id));
        return "blog";
    }
/*
<form name="search" action="#" th:action="@{/search}" method="post" target="_blank">
          <div class="ui icon inverted transparent input m-margin-tb-tiny">
            <input type="text" name="query" placeholder="Search...." th:value="${query}">
            <i οnclick="document.forms['search'].submit()" class="search link icon"></i>
          </div>
</form>
*/
@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{}


//<a href="#" th:href="@{/admin/types/{id}/input(id=${type.id})}" class="ui mini teal basic button">编辑</a>
@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() {
//        logger.info("--------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一起出现
//拦截器 拦截对/admin/**的访问 不拦截/admin ,/admin/login
@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值