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

前端 未结 2 1893
-上瘾入骨i
-上瘾入骨i 2021-01-19 02:04

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

2条回答
  •  忘掉有多难
    2021-01-19 02:55

    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
        
    
    

提交回复
热议问题