spring boot踩坑点滴记录
springboot 2.x 自动化注入的实现的jar包
以redis为例:
org.springframework.boot.autoconfigure.data.redis.JedisConnectionConfiguration
@ConditionalOnClass注解是指在classpath下存在指定的类的class才执行该bean的context。
@ConditionalOnMissingBean注解是指在上下文中没有指定的类的bean才加载该bean。
@ControllerAdvice表示当前类是对controller的切面,是为了作为controller的全局切面使用,在其中申明的@ExceptionHandler、@InitBinder、@ModelAttribute作用于全局。
@Order是指定当前bean的加载顺序。
@ExceptionHandler是指Controller在抛出指定异常时,封装异常处理的返回,可以是json也可以是ModelAndView.
@ControllerAdvice
@Order( value = Ordered.HIGHEST_PRECEDENCE )
public class ShiroExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
@ResponseBody
public Object unauthenticatedHandler(AuthenticationException e) {
e.printStackTrace();
return ResponseUtil.unlogin();
}
@ExceptionHandler(AuthorizationException.class)
@ResponseBody
public Object unauthorizedHandler(AuthorizationException e) {
e.printStackTrace();
return ResponseUtil.unauthz();
}
@InitBinder可以对controller请求参数进行自定义格式绑定
//绑定多个属性编辑器,都是同一类型data,不同的属性名(orderDate,shipDate)
@InitBinder
public void bindingPreparation(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, "orderDate", new MyDateEditor());
binder.registerCustomEditor(Date.class, "shipDate", new MyDateEditor2());
}
//MyDateEditor.java
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateEditor extends PropertyEditorSupport{
@Override
public String getAsText() {
//获取属性值
Date date = (Date) getValue();
DateFormat dateFormat = new SimpleDateFormat("yyyyMM--dd");
String str = dateFormat.format(date);
String mydate = str.substring(0,4)+str.substring(4,6)+"--"+str.substring(8,10);
System.out.println(mydate);
return mydate;
}
//text: 201801--10
@Override
public void setAsText(String text) throws IllegalArgumentException {
DateFormat dateFormat = new SimpleDateFormat("yyyyMM--dd");
try {
System.out.println(dateFormat.parse(text));
//设置属性值
setValue(dateFormat.parse(text));
}catch (ParseException e){
System.out.println("ParseException....................");
}
}
}
@ModelAttribute
申明在方法上,用来初始化model中的属性。
springboot 与mybatis集成时,采用@MapperScan,此时如果不在yml中配置
mapper-locations: classpath:com/jerry/db/mapper/*.xml
则默认xml的路径与mapper接口路径一致。如果指定上述配置,则按配置路径走