每当方法具有自定义注释时,我都希望在控制台上打印“欢迎使用AOP”。为此,我使用了@annotation,但它似乎在我的代码中不起作用。有人知道原因吗?
我的自定义注释:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Greeting {
}
使用注释的学生班级:
public class Student {
private String name;
private String familyName;
public Student(String name, String familyName) {
super();
this.name = name;
this.familyName = familyName;
}
@Greeting
public String getFullName() {
return this.name + " " + this.familyName;
}
}
方面配置类:
@Configuration
@EnableAspectJAutoProxy
@Aspect
public class AspectConfig {
@Before("execution(* com.example.demo..*.* (..)) && @annotation(com.example.demo.Greeting)")
public void logBeforeAllMethods() {
System.out.println("Welcome to AOP");
}
最后是我的休息控制器
@RestController
public class Test {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String mainPage() {
Student student = new Student("X", "Y");
String r = student.getFullName();
return r;
}
}
要使Spring AOP在这里工作,学生应该是spring管理的bean。使用@Component注释该类并包含在组件扫描中,或者使用@Bean注释从@Configuration类将其声明为bean。
使用新运算符时,创建的Student实例不是spring容器管理的bean。
更新
您也可以重组课程。例如,可以将Aspect移至其自身的其他类。最好让配置类只包含配置条目。
@Aspect @Component public class GreetingAspect { @Before("execution(* com.example.demo..*.* (..)) && @annotation(com.example.demo.Greeting)") public void logBeforeAllMethods() { System.out.println("Welcome to AOP"); } }
和以下配置类
@Configuration @EnableAspectJAutoProxy @ComponentScan(basePackageClasses= {Student.class,GreetingAspect.class}) public class AppConfig { }
而且学生bean可以是scope原型的
@Component @Scope(scopeName="prototype") public class Student { private String name; private String familyName; public Student(String name, String familyName) { super(); this.name = name; this.familyName = familyName; } @Greeting public String getFullName() { return this.name + " " + this.familyName; } }
并从应用程序上下文中获取Student bean。
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
ApplicationContext ctx;
@Override
public void testStudent(String name, String familyName) {
Student student = ctx.getBean(Student.class,name,familyName);
student.getFullName();
}
}