MyEclipse2014快速配置Spring & Spring Testing, Spring AOP簡單使用,myeclipse2014
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;@Servicepublic class UserServiceImp implements UserService {@Overridepublic void login(String username) {// TODO Auto-generated method stubSystem.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 {@Resourceprivate UserService userService;@Testpublic 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識別@Componentpublic 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,你值得擁有.
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。