java - 使用注解的 Spring 3 的 AOP

标签 java spring aspect

我正在尝试让 Aspect 与 Spring 3 和注释一起使用。

@Aspect
public class AttributeAspect {

  @Pointcut("@annotation(com.mak.selective.annotation.Attribute)")
  public void process(){
    System.out.println("Inside Process ....");
  }

  @Around("process()")
  public void processAttribute(){
    System.out.println("Inside Actual Aspect ..");
  }
}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 <aop:aspectj-autoproxy proxy-target-class="false" />
<context:component-scan base-package="com.mak.selective.annotation.*" />
<bean name="attribute" class="com.mak.selective.annotation.AttributeAspect"/>
</beans>

我的测试来测试方面:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/springcontext/*.xml")
public class AttributeTest {

@Attribute(tableName = "firstTable", columnName = "New Column")
private void getAttribute() {
    System.out.println("Inside Attribute call...");
}

@Test
public void testAttributeAspect() {
    getAttribute();
}

}

使用此代码,我只能看到“内部属性调用...”,但方面看不到任何内容。 请指导。

Got this working by making a new Object (Component) and injected to the Junit test class.

最佳答案

很高兴看到您可以通过 XML 来实现它,但您也可以通过注释来实现它。

问题是 @Aspect 注释不是 Spring 构造型,因此扫描器不会将方面注册为 Spring Bean。只需在 @Aspect 上方或下方添加 @Service@Component 即可注册。

此外,按照标准 Spring 设计,可以直接命名 bean(例如,@Service("myNamedService")),也可以让它实现一个接口(interface)(例如,public class AttributeAspect Implements IAspect {)。

关于java - 使用注解的 Spring 3 的 AOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7500617/

相关文章:

java - 如何在java中的嵌套循环中中断if语句

java - 在插入表之前清理数据

java - 即使使用关键字 "after",AOP 方面也会在给定方法之前执行?

java - 将切面转换为原生 AspectJ 表示法

java - @Around注解: Make variable available to joinpoint without changing method signature and use it later

Java 9 + maven + junit : does test code need module-info. java 自己的,放在哪里?

java - 使用 Hibernate SQLQuery 返回 Postgres UUID

java - 如何在控制台输出上对齐字符串

java - Hibernate-Spring Security-Spring MVC版本

java - 将 CAS 与自定义登录页面一起使用