Aop使用args切點的一個錯誤:No visible constructors in class *

springAop使用args切點的一個錯誤:No visible constructors in class org.springframework.boot.context.properties.ConversionServiceDeducer$Factory

問題:

在使用args形式的aop的時候,程序跑不起來,報錯如上,我當時的代碼大概是這麼寫的

@Aspect
@Component
public class MyAspect {

    @Pointcut("args(java.lang.String)")
    public void pointCut() {}

    @Before("pointCut()")
    public void beforeSay() {
        System.out.println("說話之前做點準備。。。。");
    }
}
@Service
public class HelloServiceImpl implements HelloService, CommandLineRunner {

    @Autowired
    private HelloService helloService;

    @Override
    public void run(String... args) throws Exception {
        // 預期是這裏執行say方法之前,執行切面類中beforeSay方法中的內容
        helloService.say("你好明天");
    }

    @Override
    public void say(String word) {
        System.out.println("我說:" + word);
    }
}

實際上,@Pointcut(“args(java.lang.String)”) 這個切點表達式出大問題了。 凡是參數是一個String的方法都會被去增強,想想整個項目中、包括整個spring框架中,不知道有多少這樣的方法呢,凡是加載到容器中的類都會被匹配一遍,還不知道會有多少問題呢。

正確的做法:

對這種匹配太模糊的切點,增加其他範圍限制。比如

@Pointcut("execution(* com.su.demo.aspect.HelloService.*(..)) && args(java.lang.String)")

這樣子就限定了只匹配com.su.demo.aspect.HelloService 這個類中的只有一個String類型參數的方法了。程序可以正常運行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章