自定义注解学习与使用
案例代码
1. 自定义注解@LogExecutionTime
package com. bytedance. annotation. annotation1 ;
import java. lang. annotation. ElementType ;
import java. lang. annotation. Retention ;
import java. lang. annotation. RetentionPolicy ;
import java. lang. annotation. Target ;
@Target ( ElementType . METHOD )
@Retention ( RetentionPolicy . RUNTIME )
public @interface LogExecutionTime {
}
2. 定义切面(切入点 + 通知)
package com. bytedance. annotation. annotation1 ;
import org. aspectj. lang. ProceedingJoinPoint ;
import org. aspectj. lang. annotation. Around ;
import org. aspectj. lang. annotation. Aspect ;
import org. springframework. stereotype. Component ;
@Aspect
@Component
public class LoggingAspect {
@Around ( "@annotation(LogExecutionTime)" )
public Object logExecutionTime ( ProceedingJoinPoint joinPoint) throws Throwable {
long start = System . currentTimeMillis ( ) ;
Object proceed = joinPoint. proceed ( ) ;
long end = System . currentTimeMillis ( ) ;
long offset = end - start;
System . out. println ( joinPoint. getSignature ( ) + " executed in " + offset + " ms" ) ;
return proceed;
}
}
3. 启动切面设置
package com. bytedance. annotation. annotation1 ;
import org. springframework. context. annotation. Configuration ;
import org. springframework. context. annotation. EnableAspectJAutoProxy ;
@Configuration
@EnableAspectJAutoProxy
public class AspectConfig {
}
4. 具体业务实现
package com. bytedance. annotation. annotation1 ;
import org. springframework. stereotype. Service ;
@Service
public class DemoServiceImpl {
@LogExecutionTime
public int calculate ( int n) {
int sum = 0 ;
for ( int i = 0 ; i < n; i++ ) {
sum += i;
}
return sum;
}
}
package com. bytedance. annotation. annotation1 ;
import org. springframework. beans. factory. annotation. Autowired ;
import org. springframework. web. bind. annotation. GetMapping ;
import org. springframework. web. bind. annotation. PathVariable ;
import org. springframework. web. bind. annotation. RestController ;
@RestController
public class DemoController {
@Autowired
private DemoServiceImpl demoService;
@GetMapping ( "/{num}" )
public int cal ( @PathVariable int num) {
int calculate = demoService. calculate ( num) ;
return calculate;
}
}
5. 调用方法,控制台打印输出
2023 - 11 - 03 14 : 56 : 59.780 INFO 10844 -- - [ nio- 8080 - exec- 1 ] o. s. web. servlet. DispatcherServlet : Completed initialization in 0 ms
int com. bytedance. annotation. annotation1. DemoServiceImpl. calculate ( int ) executed in 8 ms