新聞中心
如何在SpringBoot環(huán)境下使得自定義的注解能夠使用${xxx}表達式,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供禹州網(wǎng)站建設(shè)、禹州做網(wǎng)站、禹州網(wǎng)站設(shè)計、禹州網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、禹州企業(yè)網(wǎng)站模板建站服務(wù),10年禹州做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
相關(guān)依賴
org.aspectj aspectjrt org.aspectj aspectjweaver runtime
自定義注解
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface Manufactur { String value() default "" ; // 廠商編號 }
AOP
需要AOP在方法執(zhí)行器對方法上的注解進行解析處理,獲取占位符對應(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 ; } }
該類實現(xiàn)了EnvironmentAware 用于獲取Environment對象,該對象能夠獲取當前環(huán)境下的所有相關(guān)配置信息。同時通過該類的resolvePlaceholders方法能夠解析占位符對應(yīng)的內(nèi)容值。
Service中使用
@Service public class BusinessService { public static ThreadLocalcode = 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("自定義注解動態(tài)獲取屬性值:{}", sno) ; // todo return sno ; } }
在AOP中將解析后的值已經(jīng)存入到了ThreadLocal中。
測試
@RestController @RequestMapping("/business") public class BusinessController { @Resource private BusinessService bs ; @GetMapping("/{id}") public Object home(@PathVariable String id) { return bs.invoke(id) ; } }
到此一個自定義注解中支持占位符就完成了,還是非常簡單的。
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
新聞名稱:如何在SpringBoot環(huán)境下使得自定義的注解能夠使用${xxx}表達式
文章網(wǎng)址:http://www.dlmjj.cn/article/gcdhei.html