java - 字段初始化后执行方法

标签 java aop aspectj

我有一个定义数据库行访问的类。

public abstract class DBRow {
    int index;

    DBConnection connection;

    public DBRow(DBConnection con, int id) {
        connection = con;
        index = id;
    }

    public DBRow(DBConnection con) {
        this(con, -1);
    }

    public abstract String getTableName();

    private static String getFieldName(Field field) {
        ...
    }

    public void save() {
        ... (Reads all fields that are annotated with @InDB and saves them
    }

    public void load() {
        ... (Will load a row from the database or create a new one if index == -1)
    }
}

数据库中的特定行扩展了此 DBRow 类。 例如:

public class Test extends DBRow {
    @InDB
    public String vct;

    @InDB
    public int intt;

    public Test(DBConnection con, int id) {
        super(con, id);     

        vct = "test";
        intt = 123;
    }

    @Override
    public String getTableName() {
        return "test";
    }
}

调用构造函数后,应调用“load”,以便从数据库加载行或正确创建并保存行。

public aspect DBRowLoadSave {
    pointcut load() : execution(DBRow.new(*, *));

    after() : load() {
        ((DBRow)thisJoinPoint.getThis()).load();
    }
}

我的问题是,此时字段将不会被初始化,因为切入点监听 Test 母类中的构造函数调用,而不是 Test 本身。有没有一种方法可以监听子类的所有构造函数,或者有其他方法可以在类完全初始化后执行 load 方法吗?

最佳答案

execution(DBRow+.new(..)) 匹配所有子类构造函数,但包括基类。因此,您需要通过 !execution(DBRow.new(..)) 排除它。

此外,您可以通过 this() 将创建的对象直接绑定(bind)到变量,从而避免 getThis() 调用和建议中的强制转换。

public aspect DBRowLoadSave {
    pointcut load(DBRow dbRow) :
        execution(DBRow+.new(..)) &&
        !execution(DBRow.new(..)) &&
        this(dbRow);

    after(DBRow dbRow) : load(dbRow) {
        System.out.println(thisJoinPoint);
        dbRow.load();
    }
}

关于java - 字段初始化后执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27880540/

相关文章:

java - Spring 启动 : Unit test and Config file

java - bean 初始化失败;嵌套异常是 java.lang.IllegalArgumentException : Pointcut is not well-formed: expecting ')'

java - 异步服务中的 Spring 请求范围?通过 threadLocal 变量实现 ThreadScope,加上一个 AsyncAspect 来清理

java - 为什么 Spring @Value 与 @Controller 不兼容?

android - 在Gradle构建中运行AspectJ和Firebase性能监视

java - 在远程数据库中打开文件

java - Google BigQuery 的 JDBC 驱动程序?

java - 如何将List转换为Map并使Map成为对象属性的关键

spring - 无法使用 spring 获取 eclipselink 的 EntityManager 的事件 session

aop - 如何自定义 AspectJ aop.xml 位置?