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

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

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

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

相反,您应该使用像AspectJ这样的AOP解决方案,其中有大量的在线教程和示例。 但是,我会小心翼翼地尝试遵循最新版本和最佳实践的示例,因为那里有很多旧东西。

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

您可以在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(); } } 

类路径的唯一补充是:

  org.jboss.weld.se weld-se 1.1.10.Final  

注释:

 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"; } } 

描述:

    foo.Guard