2018-02-07-0.spring配置aop编程

aop基础配置

注册对象必须经过spring-config.xml这种文件的读取,可以使用注解配置(本人尚未成功,可能少了一些jar包)

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.itcast.bean.User;
import cn.itcast.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cn/itcast/d_springaop/applicationContext.xml")
public class Demo {
    @Resource(name="userService")
    private UserService us;
    
    @Test
    public void fun1(){
        us.save();
    }
    
}

我用的是servlet模拟了网络请求,为了拿到配置文件对象

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        ServletContext servletContext = request.getServletContext();
        WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        UserService us = (UserService) ac.getBean("userService");
        us.hello();
//        User user = (User) ac.getBean("user");

//        System.out.println(user);
    }

aop config文件配置如下



    
    
    

    
        
        
            
        
    

结果如下

使用aop注解编程

配置文件xml中:

xsi:schemaLocation添加

http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd

通知类中:

    @Component("UserServiceAdvice")
    @Aspect
public class UserServiceAdvice {

    @Pointcut("execution(* cn.itcast.user.service.UserService.*(..))")
    public void pc(){}

    @Before("UserServiceAdvice.pc()")
    public void before() {
        System.out.println("我是before");
    }
}

目标对象中:

@Component("userService")
public class UserService {

    public void hello() {
        System.out.println("hello啊");
    }
}

附:环绕通知有点特殊

//环绕通知
    @Around("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法
        System.out.println("这是环绕通知之后的部分!!");
        return proceed;
    }

你可能感兴趣的:(2018-02-07-0.spring配置aop编程)