SpringBoot自定義注解屬性支持占位符$「x」
環(huán)境:SpringBoot2.3.8.RELEASE + JDK1.8
本文教你如何在SpringBoot環(huán)境下使得自定義的注解能夠使用${xxx}表達(dá)式。
相關(guān)依賴
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjrt</artifactId>
- </dependency>
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <scope>runtime</scope>
- </dependency>
自定義注解
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.METHOD)
- @Documented
- public @interface Manufactur {
- String value() default "" ; // 廠商編號(hào)
- }
AOP
需要AOP在方法執(zhí)行器對(duì)方法上的注解進(jìn)行解析處理,獲取占位符對(duì)應(yīng)的值
- @Component
- @Aspect
- public class ManufacturAspect implements EnvironmentAware {
- private static final Logger logger = LoggerFactory.getLogger(ManufacturAspect.class) ;
- private Environment environment;
- @Pointcut("@annotation(com.pack.annotation.Manufactur)")
- private void info() {}
- @Before("info()")
- public void execBefore(JoinPoint jp) {
- MethodSignature sign = (MethodSignature) jp.getSignature() ;
- Method method = sign.getMethod() ;
- Manufactur manu = method.getAnnotation(Manufactur.class) ;
- String value = manu.value() ;
- logger.info("獲取到注解值:{}", value) ;
- BusinessService.code.set(this.environment.resolvePlaceholders(value)) ;
- }
- @Override
- public void setEnvironment(Environment environment) {
- this.environment = environment ;
- }
- }
該類實(shí)現(xiàn)了EnvironmentAware 用于獲取Environment對(duì)象,該對(duì)象能夠獲取當(dāng)前環(huán)境下的所有相關(guān)配置信息。同時(shí)通過(guò)該類的resolvePlaceholders方法能夠解析占位符對(duì)應(yīng)的內(nèi)容值。
Service中使用
- @Service
- public class BusinessService {
- public static ThreadLocal<String> code = new ThreadLocal<String>() ;
- private static Logger logger = LoggerFactory.getLogger(BusinessService.class) ;
- @Manufactur("${manufactur.code}-#{1 + 3}")
- public String invoke(String id) {
- String sno = code.get() ;
- logger.info("自定義注解動(dòng)態(tài)獲取屬性值:{}", sno) ;
- // todo
- return sno ;
- }
- }
在AOP中將解析后的值已經(jīng)存入到了ThreadLocal中。
測(cè)試
- @RestController
- @RequestMapping("/business")
- public class BusinessController {
- @Resource
- private BusinessService bs ;
- @GetMapping("/{id}")
- public Object home(@PathVariable String id) {
- return bs.invoke(id) ;
- }
- }
到此一個(gè)自定義注解中支持占位符就完成了,還是非常簡(jiǎn)單的。