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中的屬性。