【问题标题】:Why is my AOP aspect returning null?为什么我的 AOP 方面返回 null?
【发布时间】:2018-05-29 11:17:44
【问题描述】:

此执行前代码不起作用?它返回null,因为datap 不是从my_int_it_method() 方法设置的。 @Before 应该已经执行 my_int_it_method() 然后只有 send() 可以工作。

AOP 代码在这里:

package org.main;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class data {
    Connection con = new db_connect().connect();
    String datap;
    String test;

    @Before("execution(public String send())")
    public void my_int_it_method() {

        String query = "Select * from shapes where shape_id=?";
        PreparedStatement pstmt;
        try {
            pstmt = con.prepareStatement(query);
            pstmt.setInt(1, 2);
            ResultSet rs = pstmt.executeQuery();

            if(rs.next()) {
                datap=rs.getString("type");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public String send() {
        return datap;
    }   
}

XML 配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <aop:aspectj-autoproxy/>
    <bean name = "data" class="org.main.data" autowire="byName"/>
</beans>

这里的执行代码:

package org.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring.xml");
        data dataa = ctx.getBean("data",data.class);
        dataa.send();
    }
}

【问题讨论】:

    标签: java spring aop aspectj spring-aop


    【解决方案1】:

    问题是您在同一个类中定义了方面和目标(发送方法)。

    来自 AOP Spring 文档

    在 Spring AOP 中,不可能让切面本身成为其他切面的建议目标。类上的 @Aspect 注释将其标记为方面,因此将其排除在自动代理之外。

    换句话说,当一个类被注释@Aspect 时,它不能被代理,这是 AOP 工作所必需的。

    解决方案是将您的方面提取到一个新类。但是,这会给您带来一些其他问题,因为您将无法访问您想要设置的 datap

    老实说,我不确定您当前的示例是否最好用 AOP 解决。

    如果您想了解更多关于 AOP 的信息,请查看 AOP Spring Documentation。大量的例子就很清楚了。

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 1970-01-01
      • 2022-01-10
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多