springboot常用注解记录

springboot启动方式:
1.  @EnableAutoConfiguration + @ComponentScan 
    @EnableAutoConfiguration 注解的作用:自动配置,扫包范围是当前类(本包和子包不扫描)
    @ComponentScan("com.mf.controller"),@ComponentScan缺点:如果包很多就要写很多路径
2.@SpringBootApplication 等于@EnableAutoConfiguration + @ComponentScan 同级包和当前包
额外注解及作用:
@EnableConfigurationProperties(value={DBConfig1.class, DBConfig2.class}) // 读取配置类(由@Configuration注解的类)
@EnableAsync // 开启异步调用(在需要的方法上添加@Async)
@MapperScan // 可以不在mapper层添加注解(使用注解写sql的情况)
// @EnableAutoConfiguration
// @ComponentScan("com.mf.controller")
// 开启读取配置文件
// @EnableConfigurationProperties(value={DBConfig1.class, DBConfig2.class})
@SpringBootApplication
@EnableAsync // 开启异步调用,使用@Async
@MapperScan(basePackages = {"com.mf.mapper"}) // 可以不在mapper层添加注解
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class);
	}
}
  1. 升级到SpringBoot2之后发现(继承了WebMvcConfigurationSupport类)所有的静态资源都404了
    
    1.extends WebMvcConfigurerAdapter(已过时) overwrite addResourceHandlers()
    2.implements WebMvcConfigurer overwrite addResourceHandlers()
    3.application.properties文件直接进行修改
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/META-INF/resources/")
				.addResourceLocations("classpath:/resources/")
				.addResourceLocations("classpath:/static/")
				.addResourceLocations("classpath:/public/");
	}
}
使用@ControllerAdvice + @ExceptionHandler 全局捕获异常
    @ControllerAdvice
    @ExceptionHandler
/**
 * 异常捕获类,指定捕获com.mf.controller包下的所有类发生的异常
 *
 */
@ControllerAdvice(basePackages = "com.mf.controller")
public class GlobalExceptionHandler {

	
    /**
    *ModelAndView 返回页面
    *捕获运行时异常
    *返回json格式字符串错误信息
    *
    */
	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public Map<String, Object> errorJSON(Exception e){
		// 将错误记录在日志中。通过邮件发送给技术
		Map<String, Object> errorResultMap = new HashMap<>();
		errorResultMap.put("errorCode", 500);
		errorResultMap.put("errorMsg", "全局捕获异常系统错误");
//		e.printStackTrace();
		return errorResultMap;
	}
}
发布了47 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42428264/article/details/98473691