【问题标题】:Spring AOP - Unable to execute AspectSpring AOP - 无法执行方面
【发布时间】:2016-11-30 00:04:16
【问题描述】:

我是 Spring AOP 和注释的新手。我尝试编写一个使用 Aspect 的简单程序。我无法弄清楚我哪里出错了。它不会打印我在方面的内容。

package com.business.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@EnableAspectJAutoProxy
@Configuration
public class PrintMain {

    public static void main(String[] args) {
        // Do I always need to have this. Can't I just use @Autowired to get beans
        ApplicationContext ctx = new AnnotationConfigApplicationContext(PrintMain.class);
        CheckService ck = (CheckService)ctx.getBean("service");
        ck.print();
    }

    @Bean(name="service")
    public CheckService service(){
        return new CheckService();
    }

}

package com.business.main;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SimpleAspect {

    @Around("execution(* com.business.main.CheckService.*(..))")
    public void applyAdvice(){
        System.out.println("Aspect executed");
    }
}

package com.business.main;

import org.springframework.stereotype.Component;

@Component
public class CheckService{
    public void print(){
        System.out.println("Executed service method");
    }
}

输出:执行的服务方法

我希望打印我的方面中的内容

【问题讨论】:

    标签: java spring-aop spring-annotations


    【解决方案1】:

    我认为你的 @Component 不起作用!
    也许,您需要@ComponentScan

    @EnableAspectJAutoProxy
    @ComponentScan
    @Configuration
    public class PrintMain {
    
        public static void main(String[] args) {
            // Do I always need to have this. Can't I just use @Autowired to get beans
            ApplicationContext ctx = new AnnotationConfigApplicationContext(TNGPrintMain.class);
            CheckService ck = (CheckService)ctx.getBean("service");
            ck.print();
        }
    
        @Bean(name="service")
        public CheckService service(){
            return new CheckService();
        }
    
    }
    

    【讨论】:

    • 我必须进行两项更改才能使其工作 1) 实现接口 2) 添加 @ComponentScan.但是我想知道为什么它没有接口就不能工作......我读了一些与CGLIB相关的东西,这些东西不能通过注释来强制。其次,为什么没有 @ComponentScan 就不能工作
    • @karthik 因为你只使用了组件,但是 spring 没有将它用作 bean,这意味着 ApplicationContext 没有它。当 ApplicationContext 连接时,它需要知道谁将被连接为 bean。 ApplicationContext 不知道您是需要 Component 还是使用它,因此您需要使用 Xml 或 ComponentScan 来告诉 Spring 我有一些 bean 需要连接。
    猜你喜欢
    • 2011-09-20
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多