Can javax.interceptor be used in Java SE?

I need to use AOP to solve a specific problem, but it is a small standalone Java program (without Java EE container).

Can I use the functionality javax.interceptor, or do I need to download some third-party AOP implementation? I would rather use what comes with the Java SE SDK, if at all possible.

+5
source share
2 answers

If you are not using any container, then there will be no implementation of the Java EE interceptor API available to your application.

AOP, AspectJ, . , , , , .

Spring, Spring . , AspectJ.

+2

CDI Java SE, . - 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();
  }
}

:

<dependency>
  <groupId>org.jboss.weld.se</groupId>
  <artifactId>weld-se</artifactId>
  <version>1.1.10.Final</version>
</dependency>

:

package foo;
import java.lang.annotation.*;
import javax.interceptor.InterceptorBinding;

@Inherited @InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface Guarded {}

:

package foo;
import javax.interceptor.*;

@Guarded @Interceptor
public class Guard {
  @AroundInvoke
  public Object intercept(InvocationContext invocationContext) throws Exception {
    return "intercepted";
  }
}

<!-- 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>
+5

All Articles