AOP创建代理的两种方式

329 阅读1分钟

报错:Bean named 'xxx' is expected to be of type 'com.marchsoft.service.impl.AccountServiceImpl' but was actually of type 'com.sun.proxy.$Proxy8'

AOP创建代理的两种方式

1.基于接口,通过JDK创建代理

配置:

<aop:aspectj-autoproxy />
或
<aop:aspectj-autoproxy proxy-target-class="false"/>

2.基于类,通过CGLIB创建代理

配置

<aop:aspectj-autoproxy proxy-target-class=""/>

经典案例分析:

public interface UserDao {
    void add();
}

@Repository(value = "userDaoImpl")
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("userDaoImpl add...");
    }
}

@Component  //不可缺
@Aspect  //生成代理对象
public class UserDaoImplProxy {

    @Before(value = "execution(* com.ken.dao.UserDaoImpl.add(..))")
    public void before(){
        System.out.println("before...");
    }

    public void AfterReturning(){}

    public void After(){}

    public void AfterThrowing(){}

    public void Around(){}
}

public class Test {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

        //基于接口产生代理 proxy-target-class="false"  通过JDK创建
        UserDao userDao = context.getBean("userDaoImpl",UserDao.class);

        //基于类创建代理 proxy-target-class="true"  通过cglib创建
        //UserDaoImpl userDao = context.getBean("userDaoImpl",UserDaoImpl.class);

        System.out.println(context.getBean("userDaoImpl").getClass().getName());
        userDao.add();
    }
}