Docs. Spring. IO/spring/docs…
Official document 😃😃😃😃😃😃😃
General notes
@Component
@Configuration
Copy the code
Dao layer
@Repository
Copy the code
The service layer
@Service
Copy the code
The controller class:
1. @Controller
2. @RestController = @Controller + @ResponseBody
3Notification class, aspect programming, in fact, is to@RequestMappingWith multiple annotations,@ControllerAdvice(assignableTypes = {myController.class}) internal common annotations3.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: Applies to all@RequestMappingAnnotation methods that initialize the data binder before execution, such as:@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}
3.5 @ResponseStatus(httpstatus. INTERNAL_SERVER_ERROR) returns the status4. @RequestMapping
5. ResponseEntity objectCopy the code
Injection properties
@Data
@ConfigurationProperties(prefix = "anthony")
public class MyProperties {
@value(${"anthony.name"})
String name;
String age;
String info;
// Execute after the object is initialized
@PostConstruct
public void doFirst(a) {
System.out.println("name = " + name);
System.out.println("age = " + age);
System.out.println("info = " + info);
this.info = "modify"; }}/ / if it's not EnableConfigurationProperties need to MyProperties plus a @ Configuration is best
@EnableConfigurationProperties(MyProperties.class)
@RestController
public class MyController {
@Autowired
MyProperties properties;
}
Copy the code
Unit test class
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringValidatorApplicationTests {
@Test
@After
@Before
public void test(a){}}Copy the code
Validate data verification
@Data
public class MYData {
@NotNull(message = "The state cannot be empty.")
@Min(value = 18,groups = Adult.class)
@PositiveOrZero(message = "Positive or zero.")
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 = "The state cannot be empty.")
@Min(value = 18,message = "Wrong")
@PositiveOrZero(message = "Positive or zero.")
@Validated({mydata.adult. Class}) only validates the groups tag, so be careful@ValidGroup detection cannot be performed. BindingResult Can obtain failure resultsCopy the code
aop
1Custom log annotations@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
String value(a) default "";
}
2Custom log AOP classes@Aspect
@Component
public class LogAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
// You can wrap the @log annotated class around the notification
@Pointcut("@annotation(com.spring.springvalidator.aop.Log)")
public void logPointCut(a) {}// Wrap around the notification
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
Object result =null;
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// Record the request
logger.info("DoBefore: request address:" + request.getRequestURL().toString());
logger.info("doBefore : HTTP METHOD : " + request.getMethod());
logger.info("doBefore : CLASS_METHOD : " + point.getSignature().getDeclaringTypeName() + "."
+ point.getSignature().getName());
// Execute method
result = point.proceed();
logger.info("DoBefore: Method parameter:" + Arrays.toString(point.getArgs()));
logger.info("DoBefore: method return value:" + result);
logger.info("doAfterReturning");
return result;
} catch (Exception e) {
logger.error("doAfterThrowing : {} ", e.getMessage());
throw new RuntimeException("runtime exception");
} finally {
logger.info("doAfter"); }}Copy the code
@Aspect
@Component
public class WebLogAspect2 {
private static final Logger logger = LoggerFactory.getLogger(WebLogAspect2.class);
/ / point of tangency
/ / two.. Represents all subdirectories, the last two in parentheses.. Represents all parameters
@Pointcut("execution( * com.spring.springvalidator.web.*.*(..) )")
public void logPointCut(a) {}// Pre-notification
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
logger.info("doBefore");
}
// Successful return
@AfterReturning("logPointCut()")
public void doAfterReturning(JoinPoint joinPoint){
logger.info("doAfterReturning");
}
// Return on failure
@AfterThrowing("logPointCut()")
public void doAfterThrowing(JoinPoint joinPoint){
logger.info("doAfterThrowing");
}
// Pre-notification
@After("logPointCut()")
public void doAfter(JoinPoint joinPoint){
logger.info("doAfter"); }} The order of execution is generally:doBefore do(controller)DoAfter doAfterReturning\doAfterThrowing or surrounding notification, @Around("logPointCut()")
public Object aroundLog(ProceedingJoinPoint pjp) {
Object reValue = null;
try {
// Request parameters:
Object[] args = pjp.getArgs();
logger.info("doBefore");
reValue = pjp.proceed(args);
logger.info("Success return value: {}", reValue);
logger.info("doAfterReturning");
return reValue;
} catch (Throwable throwable) {
logger.info("doAfterThrowing");
throw new RuntimeException(throwable);
} finally {
logger.info("doAfter");
}
}
doBefore doAfterReturning/doAfterThrowing doAfter
Copy the code
The interceptor
@Configuration
public class WebConfig implements WebMvcConfigurer {
/** * Add interceptor *@param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/ / set
System.out.println("Front intercept 1");
return true; }}); registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/ / set
System.out.println(handler);
System.out.println("Front intercept 2");
response.setStatus(400);
return false; }}); }}Copy the code