Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use javax.interceptor in a Java SE environment?

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.

like image 384
Kevin Pauli Avatar asked Feb 08 '13 17:02

Kevin Pauli


2 Answers

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>
like image 136
McDowell Avatar answered Oct 17 '22 07:10

McDowell


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.

like image 40
Niall Thomson Avatar answered Oct 17 '22 07:10

Niall Thomson