• MyEclipse2014高速配置Spring & Spring Testing, Spring AOP简单使用


    1.新建项目

    2.右击项目,如图,利用myeclipse自己主动导入spring

    3.在弹出的对话框中一直next到最后,在最后的页面中勾选Spring Testing,完毕.


    4.在src下的applicationContext.xml里,点击namespaces,勾选aop和context


    5.在上图的底部分别进入aop和context界面,

        5.1在aop界面右击beans,加入<aop:aspectj-autoproxy>,这个的作用是启用aspectj类型的aop功能.


        5.2 在context界面右击beans,加入<context:component-scan>,并在右边的elemen details识图中填写base-package和选择annotation-config

    base-package的作用是,让spring自己主动扫描存在注解的包并注冊为spring beans.(我这里的包均以glut开头)

    annotation-config的作用大概是启用注解.(doc里面大致的意思......)




    6.创建UserService接口,UserServiceImp实现类还有MyTest測试类.

    文件夹结构:


    package glut.service;
    
    public interface UserService {
    	void login(String username);
    }
    

    package glut.serviceImp;
    
    import org.springframework.stereotype.Service;
    
    import glut.service.UserService;
    
    @Service
    public class UserServiceImp implements UserService {
    
    	@Override
    	public void login(String username) {
    		// TODO Auto-generated method stub
    		System.out.println(username + " has login");
    	}
    
    }
    

    package glut.test;
    
    import javax.annotation.Resource;
    
    import glut.service.UserService;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    //启用Spring JUnit
    @RunWith(SpringJUnit4ClassRunner.class)
    //载入指定的配置文件
    @ContextConfiguration(locations = "classpath:applicationContext.xml")
    public class MyTest {
    	@Resource
    	private UserService userService;
    
    	@Test
    	public void test() {
    		userService.login("leo");
    	}
    }
    

    測试结果:


    7.接下来測试AOP功能,新建一个切面类


    package glut.aspect;
    
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    //声明为切面
    @Aspect
    //切面也要作为component识别
    @Component
    public class MyAspect {
    	//execution(随意类型  glut..随意包.随意类(随意參数)
    	@Pointcut("execution(* glut..*.*(..))")
    	public void myPointCut() {
    	};
    
    	//调用poincut指定的方法前运行beforeMethod
    	@Before("myPointCut()")
    	public void beforeMethod() {
    		System.out.println("This is before method");
    	}
    
    	//调用poincut指定的方法后运行afterMethod
    	@After("myPointCut()")
    	public void afterMethod() {
    		System.out.println("This is after method");
    	}
    }
    

    最后再看一次測试结果:




    MyEclipse2014,你值得拥有.

  • 相关阅读:
    DS博客作业05--查找
    DS博客作业04--图
    数据结构-栈,队列
    我の第六篇博客
    我の第五篇博客
    我の第四篇博客
    我の第三篇博客
    我の第二篇博客
    Java 购物车大作业01
    有理数类的设计
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/7060048.html
Copyright © 2020-2023  润新知