Spring AOP Summary part2

well, let`s learn about how to use aop annotations and the implements of aop. 

at first @Aspect declares that this class is a aspects class & @Compoment declare a java bean that pass the control right to spring ,also you can replace it with @Service. if you have a charge spring, you can well understancd.

second, we talk about @Before & @After & @AfterThrowing & @AfterReturning & @Round, let`s take a common  example with try catch and return statement.

// @Around
try{
    //@Before
    jointPoint.proceed();
}catch(Throwable throwable){
    //@AfterThrowing
}finally{
    //@After
}
//@AfterReturning
//@Around

except the @Around annontation, you can delive the JointPoint which can help you gain the cut method name & params & other things. when you use @AfterThrowing,you can deliver another parameter Throwable, where you can acquire the accurate Exception with instanceof. the statements "jontPoint.proceed" is the real method that was invoked by java reflect mechanism.

thrid, i want to search into the aop under multi therad situation, as we know, we code many controller with @Scope default value singleton, it was easy for spring to in charging of the liftcyle of  contrllers or servlets, but if we dim a global variable in a controller and in different request method we set and get the variable. it may be thread unsafe, and may be influence the response. but if we use @Scope value is prototype, it was difficute for spring manage the controller. so does as aop classs.

let`s see the aspect code:

@Aspect
@Service
public class GottaAspect{


    private HttpServletRequest request=null;
    private HttpServletResponse response=null;
    
    @PointCut("execution=(* com.song.gotta.*.*(..))")
    public void pointCut(){}

    @Before("pointCut()")
    public void before(JointPoint jointPoint){
            
        List<Object> args= Arrays.asList(jointPoint.getArgs())
        request = (HttpServletRequest)args[0];
        response = (HttpServletResponse)args[1];
        
    } 

    @AfterrReturning("pointCut()")
    public void returning(){

        // do with request

    }


}

 with the multi requests, it was likely that a thread request instance was replaced with another request. so keep the rule in mind, that do not declare variables besides the method, that is say, you should make the variable private access & in a method. so in the returing method , you should acquire request, response agin and remove the first two declare statements.

since we have learned how to use aop, a question was issued that why aop can cut a method, the same question is, how we can implement a feature to realised the method aspects cut。well, next section we will talk about the problems, you had better know the java reflect & design patterns & java bytecode.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章