Run code before and after the method?

At the service level, I have classes that look something like this:

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 a session, and then complete its closure. I would rather do something with annotations, but I don't know where to start. How other people do something like this:

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

where the method annotated using @TelnetTransaction , opens and passes in the TelnetSession object.

Thanks,

James

+7
java dependency-injection annotations
source share
4 answers

Before and after is an aspect of programming.

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

+13
source share

If you are not doing something ropey, you want to get the object that delegates the service object, with execution. There is no reason for both types to implement exactly the same interface, and good reasons why they should not. There are several ways to achieve this:

  • Just do it manually. I suggest always starting out like this before hitting the code generation.
  • Use a dynamic proxy. Unfortunately, java.lang.reflect.Proxy requires adding an interface.
  • To create code, use APT (or at least annotation tools in 1.6 javac). A Java source is simpler than bytecode, but I don't know any good libraries for generating Java source code.
  • Use the Execute Around idiom manually - verbose and clumsy.
+2
source share

As duffymo says, AOP is the way to go. I suggest you get a copy

AspectJ in action

This is written by Ramnivas Laddad, Spring Commander, and it fully and clearly covers both Spring AOP and "real" AspectJ.

For development, you should use the AspectJ Developer Tools for Eclipse, or better yet, the SpringSource Tool Suite (it contains AJDT).

+1
source share

Spring AOP will be your best choice if you are already using this. If you need a runtime injection, you will need to use AspectJ. I remember reading Spring does not support such an injection

0
source share

All Articles