学习笔记-Spring(四)

Spring框架的全部教程,详细点这里
注解方式配置AOP

1 注解配置业务类

@Component("ts")
public class TeacherService

2 注解配置切面

//@Aspect 注解表示这是一个切面
//@Component 表示这是一个bean,由Spring进行管理
//@Around(value = "execution(* com.spring.service.TeacherService.*(..))") 
//表示对com.spring.service.TeacherService这个类中的所有方法进行切面操作
@Aspect
@Component
public class LoggerAspect {
    @Around(value="execution(* com.spring.service.TeacherService.*(..))")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("start log:" + joinPoint.getSignature().getName());
        Object object = joinPoint.proceed();
        // 就是将来与某个核心功能编织之后,用于执行核心功能的代码
        System.out.println("end log:" + joinPoint.getSignature().getName());
        return object;

    }
}

3 applicationContext.xml

<context:component-scan base-package="com.spring.aspect"/>
    <context:component-scan base-package="com.spring.service"/>
    <aop:aspectj-autoproxy/>

4 运行测试

Spring 注解方式测试
applicationContext.xml

<context:component-scan base-package="tt"/>
//1. @RunWith(SpringJUnit4ClassRunner.class) 
//  表示这是一个Spring的测试类
//2. @ContextConfiguration("classpath:applicationContext.xml")
//  定位Spring的配置文件
//3. @Autowired 给这个测试类装配对象
//4. @Test 测试逻辑,打印对象的名称

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class teee {
    @Autowired
    Student student;

    @Test
    public void test() {
        System.out.println(student.getName());
    }

}

猜你喜欢

转载自blog.csdn.net/qq_36653267/article/details/79366302