MyEclipse2014快速配置Spring & Spring Testing, Spring AOP簡單使用,myeclipse2014

來源:互聯網
上載者:User

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,你值得擁有.

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.