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

前端 未结 2 1861
-上瘾入骨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:40

    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.

    0 讨论(0)
  • 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:

    <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>
    
    0 讨论(0)
提交回复
热议问题