point cut

mbskvtky  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(364)

我正在根据应用程序属性文件中存在的切入点的数量创建aspectjexpressionpointcutadvisor。它正在创建没有错误的对象,但是切入点没有被触发。

**注意:**需要根据属性文件中的切入点表达式的数量动态创建bean(不同)。

应用程序属性文件

pointcut.expression.projectUpdate[0]= execution(* com.abc.app.service.impl.TestServiceImpl.updateProjectDetails(..))
pointcut.expression.projectUpdate[1]= execution(* com.abc.app.service.impl.TestServiceImpl.cancelProject(..))
pointcut.expression.projectUpdate[2]= execution(* com.abc.app.service.impl.TestCSATRatingServiceImpl.saveRatingDetails(..))

testconfig.class类

@Configuration
public class TestConfig implements BeanFactoryAware {

    @Autowired
    private PointcutExprProperties pcExprProp;

    @Autowired(required=false)
    private ProjectUpdateAspect projectUpdateAdvice;

     private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @PostConstruct
    public void configure() {
        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
        int i=1;
        for(String pointCut : pcExprProp.getProjectUpdate()) {
            AspectJExpressionPointcutAdvisor projectUpdateAdvisor = new AspectJExpressionPointcutAdvisor();
            projectUpdateAdvisor.setExpression(pointCut);
            projectUpdateAdvisor.setAdvice(projectUpdateAdvice);
            configurableBeanFactory.registerSingleton("beanName_"+i, projectUpdateAdvisor);
            i++;
        }
    }
}

projectupdateaspect.class类

@Component
@Aspect
public class ProjectUpdateAspect implements AfterReturningAdvice {

    private static final Logger log = LoggerFactory.getLogger(ProjectUpdateAspect.class);

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        try {
            // some thing
        }catch (Exception exception) {
            log.error("Error while processing ProjectUpdateAspect",exception);
        }

    }
}

PointCutExpr属性

@Configuration
@ConfigurationProperties(prefix = "pointcut.expression")
@Validated
public class PointcutExprProperties {

    @NotNull
    private List<String> projectCreate;

    @NotNull
    private List<String> projectUpdate;

    public List<String> getProjectCreate() {
        return projectCreate;
    }

    public void setProjectCreate(List<String> projectCreate) {
        this.projectCreate = projectCreate;
    }

    public List<String> getProjectUpdate() {
        return projectUpdate;
    }

    public void setProjectUpdate(List<String> projectUpdate) {
        this.projectUpdate = projectUpdate;
    }
}

请告诉我如何解决这个问题。

vxqlmq5t

vxqlmq5t1#

我建议你这样做:
你没有把你的“方面”定义为 @Component @Aspect 但要让它实现 MethodInterceptor .
你创造了 AspectJExpressionPointcut 属性文件中的值。
你注册了一个 DefaultPointcutAdvisor (使用切入点和拦截器配置)作为bean。
另请参阅我的答案(更新3)和我刚刚为您更新的github示例存储库,以便包括从中读取切入点 application.properties .

相关问题