Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code before and after method?

In the service layer I have a classes that look something like:

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

In many classes I have to declare and open session and then at the end close it. I'd rather do something with annotations but I've got no idea where to start. How do other people do something like this:

class MyService {
    @TelnetTransaction
    public doSomething() {
        session.execute("blah");
    }
}

where a method annotated with @TelnetTransaction instantiates, opens and passes in the TelnetSession object.

Thanks,

James

like image 561
James Avatar asked Sep 27 '10 15:09

James


2 Answers

Before and after is what aspect oriented programming is for.

Spring handles transactions with aspects. Give Spring AOP or AspectJ a look.

like image 127
duffymo Avatar answered Nov 05 '22 00:11

duffymo


Unless you are doing something ropey, you want to end up with an object that delegates to a service object, with the execute around. There is no reason for both types to implement exactly the same interface, and good reasons why they should not. There are a number of ways of ending up with this:

  • Just do it by hand. I suggest always starting off like this before hitting code generation.
  • Use a dynamic proxy. Unfortunately java.lang.reflect.Proxy requires you to add an interface.
  • Use APT (or at least the annotation processing facilities in 1.6 javac) to generate the code. Java source is easier than bytecode, but I don't know of any good libraries for Java source code generation.
  • Use the Execute Around idiom by hand - verbose and clumsy.
like image 45
Tom Hawtin - tackline Avatar answered Nov 05 '22 00:11

Tom Hawtin - tackline