spring学习(四):AOP注解方式

一、service类加注解

常规注解,bean的注解

package service;

import org.springframework.stereotype.Component;

@Component("myService")
public class MyService {
	public void doMyService() {
		System.out.println("This is my service");
	}
}


二、aspect类加注解

component注解bean类,aspect注解表示切面,around注解放到方法上

package aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {
	@Around(value="execution(* service.MyService.*(..))")
	public Object function(ProceedingJoinPoint joinPoint) throws Throwable{
		System.out.println("start: "+joinPoint.getSignature().getName());
		Object object = joinPoint.proceed();
		System.out.println("end: "+joinPoint.getSignature().getName());
		return object;
	}
}


三、配置文件

浏览包,再加个aop



 
 	
 	
 	
 


四、运行测试

同上

五、测试类注解化

将主函数去掉,变成测试函数

配置文件,service类和aspect类同上

1. @RunWith(SpringJUnit4ClassRunner.class)
表示这是一个Spring的测试类

2. @ContextConfiguration("classpath:applicationContext.xml")
定位Spring的配置文件

3. @Autowired
给这个测试类装配MyService对象

4. @Test
测试逻辑,在此运行

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import service.MyService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MyTest {
	@Autowired
	MyService ms;
	@Test
	public void test() {
		ms.doMyService();
	}
	/*
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
		MyService ms = (MyService) context.getBean("myService");
		ms.doMyService();
	}*/
}



你可能感兴趣的:(java,spring)