Spring-业务层接口案例

107 阅读2分钟

对项目进行业务层接口执行监控

public interface AccountService{
    void save(Account account);
    
    void delete(Integer id);
    
    void update(Account account);
    
    List<Account> findAll();
    
    Account findById(Integer id);
}

我们要用AOP,动态加上功能

图片.png

实现步骤

1.定义切入点(务必要绑定到接口上,而不是接口实现类上)

2.制作AOP环绕通知,完成测量功能

3.注解配置AOP

4.开启注解驱动支持

项目原本

service文件夹下的AccountService.class

public interface AccountService{
    void save(Account account);
    
    void delete(Integer id);
    
    void update(Account account);
    
    List<Account> findAll();
    
    Account findById(Integer id);
}

dao文件夹下的AccountDao

public interface AccountDao{
    @Insert("insert into account(name,money)values(#{name},#{money})")
    void save(Account account);
    
    @Delete("delete from account where id = #{id}")
    void delete(Integer id);
    
    @Update("update account set name = #{name},money=#{money} where id =#{id}")
    void update(Account account);
    
    @Select("Select * from account")
    List<Account> findAll();
    
    @Select("select * from account where id = #{id}")
    Account findById(Integer id);
}

Test测试文件

//设定spring专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class)

//测试文件里必须写:设定加载的spring上下文对应的配置
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest{
    @Autowired
    private AccountService accountService;
    
    @Test
    public void testFindById(){
        Account ac = accountService.findById(2);
        System.out.println(ac);
    }
    
    @Test
    public void testFindAll(){
        List<Account> list = accountService.findAll();
        System.out.println(list);
    }
}
实操

1.现在pom.xml中导入对应依赖

2.定义切入点(被挖走的共性功能) RunTimeAdvice

//5.告诉Spring加载,这是一个通知类,扫描他
@Component
@Aspect

//1.切入点,监控业务层接口
//返回值任意 文件目录下的某一方法(任意Service接口下的find方法) 
@Pointcut("execution(* service.*Service.find*(..))")
public void pt(){

}

//2.通知方法
//4.使用Around的pt()切入点
@Around("pt()")
public Object runtimeAround(ProceedingJoinPoint pjp) throws Throwable{
    //6.获取
    Signature signature = pjp.getSignature();
    接口名
    String className = signature.getDeclaringTypeName());
    方法名
    String methodName = signature.getName();

    //获得开始时间
    long startTime = System.currentTimeMillis();

    //3.proceed:调用我们要检测的方法 获得参数,
    Object ret = pjp.proceed(pjp.getArgs());

    //获得结束时间
    long endTime = System.currentTimeMillis();
    
    //运行时间
    System.out.println("运行时间为:"+(endTime - startTime));
    
    return ret;
}

然后再SpringConfig

@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@import({JDBCConfig.class.MyBatisConfig.class})

把AOP注解驱动支持打开
@EnableAspectJAutoProxy
public class SpringConfig{

}