是否可以在Java SE环境中使用javax.interceptor?

Kev*_*uli 5 java aop java-ee cdi

我需要使用AOP来解决特定问题,但它是一个小型的独立Java程序(没有Java EE容器).

我可以使用javax.interceptor功能,还是必须下载一些第三方AOP实现?如果可能的话,我宁愿使用Java SE SDK附带的东西.

McD*_*ell 6

您可以在Java SE中使用CDI,但必须提供自己的实现.以下是使用参考实现的示例 - 焊接:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

类路径的唯一补充是:

<dependency>
  <groupId>org.jboss.weld.se</groupId>
  <artifactId>weld-se</artifactId>
  <version>1.1.10.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

注释:

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

@Inherited @InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface Guarded {}
Run Code Online (Sandbox Code Playgroud)

拦截器实施:

package foo;
import javax.interceptor.*;

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

描述:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)


Nia*_*son 2

如果您不使用任何类型的容器,那么您的应用程序将无法使用 Java EE 拦截器 API 的实现。

相反,您应该使用 AOP 解决方案,例如 AspectJ,在线有大量教程和示例。然而,我会小心地尝试坚持遵循最新版本和最佳实践的示例,因为那里有很多旧的东西。

如果您已经在使用 Spring 框架,那么 Spring AOP 可能会满足您的要求。尽管它没有为您提供 AspectJ 的所有功能,但它会更容易集成到您的应用程序中。