SpringBoot自定义注解属性支持占位符$「x」

环境:SpringBoot2.3.8.RELEASE + JDK1.8

本文教你如何在SpringBoot环境下使得自定义的注解能够使用${xxx}表达式。

相关依赖

 
            org.aspectj 
            aspectjrt 
 
 
            org.aspectj 
            aspectjweaver 
            runtime 
 

自定义注解

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
@Documented 
public @interface Manufactur { 
    String value() default "" ; // 厂商编号 
} 

AOP

需要AOP在方法执行器对方法上的注解进行解析处理,获取占位符对应的值

@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 ; 
    } 
     
} 

该类实现了EnvironmentAware 用于获取Environment对象,该对象能够获取当前环境下的所有相关配置信息。同时通过该类的resolvePlaceholders方法能够解析占位符对应的内容值。

Service中使用

@Service 
public class BusinessService { 
     
    public static ThreadLocal code = new ThreadLocal() ; 
     
    private static Logger logger = LoggerFactory.getLogger(BusinessService.class) ; 
     
    @Manufactur("${manufactur.code}-#{1 + 3}") 
    public String invoke(String id) { 
        String sno = code.get() ; 
        logger.info("自定义注解动态获取属性值:{}", sno) ; 
        // todo 
        return sno ; 
    } 
     
} 

在AOP中将解析后的值已经存入到了ThreadLocal中。

测试

@RestController 
@RequestMapping("/business") 
public class BusinessController { 
     
    @Resource 
    private BusinessService bs ; 
     
    @GetMapping("/{id}") 
    public Object home(@PathVariable String id) { 
        return bs.invoke(id) ; 
    } 
     
} 

到此一个自定义注解中支持占位符就完成了,还是非常简单的。