在方法之前和之后执行代码?

Jam*_*mes 7 java annotations dependency-injection

在服务层我有一个看起来像这样的类:

class MyService {
    public doSomething() {
        TelnetSession session = new TelnetSession();
        session.open("username", "password");
        session.execute("blah");
        session.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

在许多类中,我必须声明并打开会话,然后在最后关闭它.我宁愿用注释做点什么,但我不知道从哪里开始.其他人如何做这样的事情:

class MyService {
    @TelnetTransaction
    public doSomething() {
        session.execute("blah");
    }
}
Run Code Online (Sandbox Code Playgroud)

使用@TelnetTransaction实例化注释的方法,打开并传入TelnetSession对象.

谢谢,

詹姆士

duf*_*ymo 13

之前和之后是面向方面的编程.

Spring处理与方面的事务.给Spring AOP或AspectJ看一看.

  • 而且,如果您想自己创建,请查找代理模式. (2认同)