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
functionality, or do I have to download some 3rd-party AOP implementation? I'd rather use what comes with the Java SE SDK if at all possible.
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:
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>1.1.10.Final</version>
</dependency>
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:
<!-- META-INF/beans.xml -->
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<interceptors>
<class>foo.Guard</class>
</interceptors>
</beans>
If you are not using a container of any sort then there will not be an implementation of the Java EE interceptor API available to your application.
You should instead look to use an AOP solution like AspectJ, for which there is a large amount of tutorials and examples online. However, I would be careful to try to stick to examples that follow the newest versions and best practices since there is a lot of old stuff out there.
If you are already using the Spring framework then Spring AOP may meet your requirements. This will be significantly easier to integrate into your application, although it does not give you all of the features of AspectJ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With