4.5. Interceptor prepared in S2Aop

4.5.1. TraceInterceptor

TraceInterceptor is Interceptor to handle trace processing as "Crosscutting Concern".
As an example, an aspect is applied to the following Service class.

module Example
  class Service
    s2comp
    def add(a, b) {
      puts "#{self.class.superclass.name}.add called."
      return a + b
    end
  end
end

Please create the following executable files.

  • TraceInterceptor is aspected to a service component by the S2ApplicationContext.aspect method
  • A container is generated by the S2ApplicationContext.create method
  • A Service component is acquired by the S2Container.get_component method.
  • The add method of the Service component is carried out.
require 's2container'
require 'example'

Seasar::Container::S2ApplicationContext.aspect(:pattern => Example::Service, :interceptor => Seasar::Aop::Interceptor::TraceInterceptor.new)
container = Seasar::Container::S2ApplicationContext.create
service   = container->get(Service)

p service.add(2, 3)

when you execute above script, when the add method of the service class was carried out, TraceInterceptor outputs log.

% ruby run.rb
D, [2009-01-01] DEBUG -- Seasar::Aop::Interceptor::TraceInterceptor: before : Example::Service.add([2, 3])
Example::Service.add called.
D, [2009-01-01] DEBUG -- Seasar::Aop::Interceptor::TraceInterceptor: after  : Example::Service.add([2, 3]) : 5 : 0.002727
5
%
[Note]NOTE

This Example is located at "example/example10".


4.5.2. Implementing Interceptor

When implementing custom-made Interceptor, please create the class which implements the call method. Let's create following Interceptor as an example.

module Example
  class SampleInterceptor
    def call(invocation)
      puts 'Before'            # <-- Processing before calling following Interceptor or a following actual method
      result = invocation.proceed
      puts 'After'             # <-- Processing after calling following Interceptor or a following actual method
      return result
    end
  end
end

Execution of MethodInvocation.proceed method will call following Interceptor or a following actual method. If two or more Aspects are defined as one component, as-follows execution is carried out.

  • The Before part of Interceptor is performed in order of registration of Aspect.
  • After performing the Before part of the last Interceptor, a component's own method is called.
  • The After portion of Interceptor is performed by the order of reverse of registration of Aspect.

The instance for an aspect, method, method arguments, etc. are acquirable through MethodInvocation passed by the argument of Interceptor::invoke method.

[Note]NOTE

This Example is located at "example/example11".



© Copyright The Seasar Foundation and the others 2008-2009, all rights reserved.