Spring - 平常開發使用技巧

docs.spring.io/spring/docs…html

官方文檔 😃😃😃😃😃😃😃java

通用註解

@Component

@Configuration
複製代碼

dao層

@Repository
複製代碼

service 層

@Service
複製代碼

controller 類的:

1. @Controller 
2. @RestController  = @Controller +  @ResponseBody

3. 通知類,切面編程,其實就是給@RequestMapping 上加了多元註解,
@ControllerAdvice(assignableTypes = {MyController.class}) 
    內部經常使用註解
3.1  @ExceptionHandler({Throwable.class}) 
  @ExceptionHandler({Throwable.class})
    public ResponseEntity<String> res(Throwable throwable){
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(throwable.getMessage());
    }        
        
        
3.2  @ModelAttribute("acceptLanguage") 
     @ModelAttribute
     public void addAttribute(Model model) {
        model.addAttribute("attribute",  "The Attribute");
    }
        
3.3 @CookieValue
3.4 @InitBinder  : 應用到全部@RequestMapping註解方法,在其執行以前初始化數據綁定器 ,好比:
	 @InitBinder
     public void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
        
    }
   
3.5 @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 返回狀態
		
     
4. @RequestMapping 
 
    
5. ResponseEntity 對象 
複製代碼

注入屬性

@Data
@ConfigurationProperties(prefix = "anthony")
public class MyProperties {

	@value(${"anthony.name"})
    String name;

    String age;

    String info;

    
    //在對象初始化以後立 馬執行 
    @PostConstruct
    public void doFirst() {
        System.out.println("name = " + name);

        System.out.println("age = " + age);

        System.out.println("info = " + info);

        this.info = "modify";
    }

}

// 若是不用EnableConfigurationProperties 須要將MyProperties加上一個@Configuration最好
@EnableConfigurationProperties(MyProperties.class) 
@RestController
public class MyController {

    @Autowired
    MyProperties properties;
}    
複製代碼

單元測試類

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringValidatorApplicationTests {

    @Test
    @After
    @Before
    public void test(){
        
    }

}
複製代碼

validate 數據校驗

@Data
public class MYData {


    @NotNull(message = "狀態不能爲空")
    @Min(value = 18,groups = Adult.class)
    @PositiveOrZero(message = "正數或者0")
    private Integer age;

    public interface Adult{}

    public interface Minor{}
    
}

    @RequestMapping("/live")
    public String live(@Validated({MYData.Adult.class}) MYData foo, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                //...
            }
            return "fail";
        }
        return "success";
    }

    @NotBlank
    @NotEmpty
    @NotNull(message = "狀態不能爲空")
    @Min(value = 18,message = "錯了")
    @PositiveOrZero(message = "正數或者0")


@Validated({MYData.Adult.class}) 只會對 groups標記的作校驗 其餘不會進行 ,因此要麼你注意一點
@Valid 不能夠進行分組檢測
BindingResult 能夠獲取失敗結果
複製代碼

aop

1. 自定義log註解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    String value() default "";
}

2. 自定義 log aop 類

@Aspect
@Component
public class LogAspect {


    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // 能夠將 加上 @log 註解的類 環繞通知
    @Pointcut("@annotation(com.spring.springvalidator.aop.Log)")
    public void logPointCut() {
    }


    //環繞通知
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result =null;
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 記錄下請求內容
            logger.info("doBefore : 請求地址 : " + request.getRequestURL().toString());
            logger.info("doBefore : HTTP METHOD : " + request.getMethod());
            logger.info("doBefore : CLASS_METHOD : " + point.getSignature().getDeclaringTypeName() + "."
                    + point.getSignature().getName());
            // 執行方法
            result = point.proceed();

            logger.info("doBefore : 方法參數 : " + Arrays.toString(point.getArgs()));

            logger.info("doBefore : 方法返回值 : " + result);

            logger.info("doAfterReturning");
            return result;

        } catch (Exception e) {

            logger.error("doAfterThrowing : {} ", e.getMessage());
            throw new RuntimeException("runtime exception");
        } finally {
            logger.info("doAfter");
        }
        
    }

複製代碼
@Aspect
@Component
public class WebLogAspect2 {

    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect2.class);

    //切點
    //兩個..表明全部子目錄,最後括號裏的兩個..表明全部參數
    @Pointcut("execution( * com.spring.springvalidator.web.*.*(..))")
    public void logPointCut() {
    }

    //前置通知 
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        logger.info("doBefore");

    }
    
    // 成功返回
    @AfterReturning("logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint){
        logger.info("doAfterReturning");
    }
    // 失敗返回
    @AfterThrowing("logPointCut()")
    public void doAfterThrowing(JoinPoint joinPoint){
        logger.info("doAfterThrowing");
    }

	//前置通知 
    @After("logPointCut()")
    public void doAfter(JoinPoint joinPoint){
        logger.info("doAfter");
    }
}


執行順序 通常是 :
doBefore do(controller) doAfter doAfterReturning\doAfterThrowing 或者 環繞通知, @Around("logPointCut()") public Object aroundLog(ProceedingJoinPoint pjp) {
        Object reValue = null;
        try {
            // 請求參數 : 
            Object[] args = pjp.getArgs();
            logger.info("doBefore");

            reValue = pjp.proceed(args);

            logger.info("成功返回值 : {} ", reValue);
            logger.info("doAfterReturning");
            return reValue;
        } catch (Throwable throwable) {
            logger.info("doAfterThrowing");
            throw new RuntimeException(throwable);
        } finally {
            logger.info("doAfter");
        }
    }

  doBefore  doAfterReturning/doAfterThrowing   doAfter
複製代碼

攔截器

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /** * 添加攔截器 * @param registry */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // 設置
                System.out.println("前置攔截1");
                return true;
            }
        });

        registry.addInterceptor(new HandlerInterceptor() {

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // 設置

                System.out.println(handler);

                System.out.println("前置攔截2");
                response.setStatus(400);
                return false;
            }
        });
    }

}
複製代碼
相關文章
相關標籤/搜索