I need to use AOP to solve a particular issue, but it is a small standalone Java program (no Java EE container).
Can I use javax.interceptor functiona
You can use CDI in Java SE but you have to provide your own implementation. Here's an example using the reference implementation - Weld:
package foo;
import org.jboss.weld.environment.se.Weld;
public class Demo {
public static class Foo {
@Guarded public String invoke() {
return "Hello, World!";
}
}
public static void main(String[] args) {
Weld weld = new Weld();
Foo foo = weld.initialize()
.instance()
.select(Foo.class)
.get();
System.out.println(foo.invoke());
weld.shutdown();
}
}
The only addition to the classpath is:
org.jboss.weld.se
weld-se
1.1.10.Final
The annotation:
package foo;
import java.lang.annotation.*;
import javax.interceptor.InterceptorBinding;
@Inherited @InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface Guarded {}
Interceptor implementation:
package foo;
import javax.interceptor.*;
@Guarded @Interceptor
public class Guard {
@AroundInvoke
public Object intercept(InvocationContext invocationContext) throws Exception {
return "intercepted";
}
}
Descriptor:
foo.Guard