切面自动装配注意点

首先切面

<!--装配扫描,启动~-->
    <context:component-scan base-package="my.dear"/>
    <!--声明service对象,在此基础上可进行插入操作-->
    <!--其实际意义为声明切面,然后在切面上端和切面下端分别执行任务,最后缝合切面完成-->
    <!--<bean id="userService" class="my.dear.service.impl.UserServiceImpl"/>-->
    <bean id="userAdvice" class="my.dear.advice.UserAdvice"/>
    <aop:config>
        <!--1:进行切面分割-->
        <!--此为静止切割任何以user结尾的空返回值方法-->
        <aop:pointcut id="p1" expression="execution(void *User(..))"/>
        <!--2:声明切面-->
        <aop:aspect ref="userAdvice">
            <!--切面上端执行-->
            <aop:before method="check" pointcut-ref="p1"/>
            <!--切面下端继续-->
            <aop:after-returning method="log" pointcut-ref="p1"/>
            <!--切面失败异常执行-->
            <aop:after-throwing method="error" pointcut-ref="p1"/>
        </aop:aspect>
    </aop:config>

要注意,只声明bean的切面实行,不声明切面

且切面只声明impl 不声明接口,接口无法被创建为对象。

package my.dear.service;

public interface UserService {

    int insertUser();

    int updateUser();

    int deleteUser();

}

 

package my.dear.service.impl;

import my.dear.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Override
    public int insertUser() {
        System.out.println("insert success!");
        return 1;
    }

    @Override
    public int updateUser() {
        System.out.println("update success");
        return 1;
    }

    @Override
    public int deleteUser() {
        System.out.println("delete success!");
        return 1;
    }
}

声明完成则进行测试,在测试中context.getBean中要注意接受的bean为结尾impl的实行

package my.dear.test;

import my.dear.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AopTest {
    private ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

    @Test
    public void testOne(){
        UserService userService = (UserService) context.getBean("userServiceImpl");
        userService.insertUser();
    }
}

 

posted @ 2019-08-02 14:42  织式  阅读(386)  评论(0编辑  收藏  举报