2013-08-02 6 views
0

аннотацию:Spring AOP: Перехватчик не работает

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD}) 
public @interface DeadlockRetry { 


} 

Перехватчик:

public class DeadlockRetryMethodInterceptor implements MethodInterceptor 
{ 

    @Override 
    public Object invoke(MethodInvocation invocation) throws Throwable 
    { 
     System.err.println("I've been Intercepted!"); 
     return invocation.proceed(); 
    } 
} 

перехваченной Класс:

public class Intercepted { 


    @DeadlockRetry 
    public void interceptMe() 
    { 
     System.err.println("Above here should be a message I've been Intercepted!"); 
    } 
} 

Главная кузницы кадров:

public class Main { 
    public static void main(String[] args) 
    { 
     //Function that loads the spring-context.xml 
     SpringContext.init(); 

     Intercepted intercepted = new Intercepted(); 
     intercepted.interceptMe(); 
    } 
} 

весны-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans 
    classpath:/org/springframework/beans/factory/xml/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/tx 
    classpath:/org/springframework/transaction/config/spring-tx-3.2.xsd 
    http://www.springframework.org/schema/aop 
    classpath:/org/springframework/aop/config/spring-aop-3.2.xsd 
    http://www.springframework.org/schema/context 
    classpath:/org/springframework/context/config/spring-context-3.2.xsd"> 


    <aop:aspectj-autoproxy /> 



    <context:annotation-config/> 

    <bean id="deadlockRetryAdvice" class="com.metaregistrar.hibernate.DeadlockRetryMethodInterceptor"/> 



    <bean id="deadlockPointcutAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> 
     <property name="advice" ref="deadlockRetryAdvice"/> 
     <property name="pointcut" ref="deadlockRetryPointcut"/> 
    </bean> 


    <bean name="deadlockRetryPointcut" class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut"> 
     <constructor-arg index="0" value="com.metaregistrar.hibernate.DeadlockRetry"/> 
     <constructor-arg index="1" value="com.metaregistrar.hibernate.DeadlockRetry"/> 
    </bean> 



</beans> 

Stderr Результат:

Над здесь должен быть сообщением Я Перехватываюсь!

Ожидаемый результат Stderr:

Я Перехватывается! Выше здесь должно быть сообщение, которое я перехватил!

Что я делаю неправильно? Я был в этой проблеме целый день, и это становится довольно раздражающим ...

ответ

1

Spring AOP работает только для фасоли весны. Вы должны определить перехваченный объект как компонент в конфигурационном файле весны, получить его из контекста и вызвать метод на нем.

Это неправильная деталь.

Intercepted intercepted = new Intercepted(); 
intercepted.interceptMe(); 

Добавить это в XML-файл

А затем извлечь экземпляр из пружинной CTX

ApplicationContext ctx = // create context using the config file 

intercepted = ctx.getBean("intercepted",Intercepted.class); 

intercepted.interceptMe(); 
+0

Я уже отдалились от Spring AOP в @Aspect в AspectJ. После определения мне нужно определить почти каждый класс как компонент в контексте весны. Который, по моему мнению, не нужен. Но эй, спасибо за решение. Это ответ на эту проблему. Но не совсем то, что я искал. –

Смежные вопросы