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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值