Dedicated governance won't look at source code Faults -- spring source code parsing AOP, -- springaop

Source: Internet
Author: User

Dedicated governance won't look at source code Faults -- spring source code parsing AOP, -- springaop

Yesterday, a Daniel said that I was so arrogant that my eyes were broken and I could not see the key points. That's too much for his grandfather! To look at the character, it is better for girls. I remember seeing a boy complain, saying how the two were just getting together, and the girl had been with him for a lifetime. Don't you want to go this far? Look at He Jie, and look at the mother who took the two dolls to the building. So now girls know that some boys are not tall and handsome, but they know that they can find a good girl. However, to look at people's technical capabilities, boys are indeed better than others. We have to work hard.

Summarize the habits to be formed:

1> if you have time to do a few algorithm questions, you can use both C and JAVA, mainly training your thinking.

2> regularly read the source code of spring. Because spring is a framework and re-designed, it can cultivate a general picture.

3> Read underlying books, such as linux and virtual machines. More advanced languages are just tricks.

4> don't forget to do half of the work, such as search engine and redis. You can do it later, because your own realm will be improved and the depth will also increase.

  

The following is the question of today. I am also very good at reading the source code, so it is also very laborious to start with the easiest way. First understand its principles, and then look at the source code. After reading the source code, you can understand the principle through the source code if you encounter any problems later. The principles of spring AOP are well understood, and the code is quite simple. This is why I often ask this question when I am a newbie.

First, let's look at the overall structure of spring. The following figure shows the hand-drawn time of the high-profile image:

If you think that the words I write in the left hand cannot be ugly any more, I can show the point of connection (Joinpoint) Notification (Advice) in the right hand Aspect (Aspect) when I have time) introduction (Introduction) Target Object (AOP Proxy) Weaving)

The thing to do with AOP is to generate a proxy object and then weave it.

Generating proxy objects is a frequently asked question: Spring provides two methods to generate proxy objects, JDKProxy and Cglib. The specific method is determined by AopProxyFactory Based on the configuration of the AdvisedSupport object. The default policy is to use JDK dynamic proxy technology if the target class is an interface. Otherwise, Cglib is used to generate a proxy. Cglib is based on bytecode and uses ASM. Asm is a java bytecode control framework that can be used to dynamically generate classes or enhance the functions of existing classes. ASM can directly generate binary class files, or dynamically change the class behavior before the class is added to the JVM. Next we will focus on JDK dynamic proxy technology. This is one of the few source codes that I can understand when I am a rookie who is very helpful. Because I have read the Java design mode and written similar examples before, it will be smoother. Let's talk about this part today.

The following is a call test class:

Package dynamic. proxy; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy;/*** implement your own InvocationHandler * @ author zyb * @ since 2012-8-9 **/public class MyInvocationHandler implements InvocationHandler {// target Object private Object target; /*** constructor * @ param target Object */public MyInvocationHandler (Object target) {super (); this.tar get = target ;} /*** Method for executing the target Object */public Object invoke (Object proxy, method Method, Object [] args) throws Throwable {// print System before the method of the target object is executed. out. println ("------------------ before ----------------"); // method of executing the target Object result = method. invoke (target, args); // After the method of the target object is executed, simply print the System. out. println ("------------------- after ----------------"); return result;}/*** get the Proxy Object of the target Object * @ return Proxy Object */public Object getProxy () {return Proxy. newProxyInstance (Thread. currentThread (). getContextClassLoader (), target. getClass (). getInterfaces (), this) ;}} package dynamic. proxy;/*** interface implemented by the target object, to use JDK to generate proxy objects, you must implement an interface * @ author zyb * @ since 2012-8-9 **/public interface UserService {/*** target Method */public abstract void add () ;} package dynamic. proxy;/*** target object * @ author zyb * @ since 2012-8-9 **/public class UserServiceImpl implements UserService {/* (non-Javadoc) * @ see dynamic. proxy. userService # add () */public void add () {System. out. println ("-------------------- add ---------------") ;}} package dynamic. proxy; import org. junit. test;/*** dynamic proxy Test class * @ author zyb * @ since 2012-8-9 **/public class ProxyTest {@ Test public void testProxy () throws Throwable {// instantiate the target object UserService userService = new UserServiceImpl (); // instantiate InvocationHandler MyInvocationHandler invocationHandler = new MyInvocationHandler (userService ); // generate the proxy object UserService proxy = (UserService) invocationHandler based on the target object. getProxy (); // call the proxy object method proxy. add ();}}View Code

The execution result is as follows:
------------------ Before ------------------
-------------------- Add ---------------
------------------- After ------------------
 

The core is invocationHandler. getProxy (); Proxy called by this method. newProxyInstance (Thread. currentThread (). getContextClassLoader (), target. getClass (). getInterfaces (), this); how to generate an object.

/*** Returns an instance of a proxy class for the specified interfaces * that dispatches method invocations to the specified invocation * handler. ** <p> {@ code Proxy. newProxyInstance} throws * {@ code IllegalArgumentException} for the same reasons that * {@ code Proxy. getProxyClass} does. ** @ param loader the class loader to define the proxy class * @ param interfaces the list of interfaces for Proxy class * to implement * @ param h the invocation handler to dispatch method invocations to * @ return a proxy instance with the specified invocation handler of a * proxy class that is defined by the specified class loader * and that implements the specified interfaces * @ throws IllegalArgumentException if any of the restrictions on the * parameters that may be passed to {@ code getProxyClass }* Are violated * @ throws SecurityException if a security manager, <em> s </em>, is present * and any of the following conditions is met: * <ul> * <li> the given {@ code loader} is {@ code null} and * the caller's class loader is not {@ code null} and the * invocation of {@ link SecurityManager # checkPermission * s. checkPermission} with * {@ code RuntimePermission ("getClassLoader")} permission * denies acce Ss; </li> * <li> for each proxy interface, {@ code intf }, * the caller's class loader is not the same as or an * ancestor of the class loader for {@ code intf} and * invocation of {@ link SecurityManager # checkPackageAccess * s. checkPackageAccess ()} denies access to {@ code intf }; </li> * <li> any of the given proxy interfaces is non-public and the * caller class is not in the same {@ linkplain Package ru Ntime package} * as the non-public interface and the invocation of * {@ link SecurityManager # checkPermission s. checkPermission} with * {@ code ReflectPermission ("newProxyInPackage. {package name} ")} * permission denies access. </li> * </ul> * @ throws NullPointerException if the {@ code interfaces} array * argument or any of its elements are {@ code null }, or * if the invocation handler, {@ code h}, is * {@ Code null} */@ CallerSensitive public static Object newProxyInstance (ClassLoader loader, Class <?> [] Interfaces, InvocationHandler h) throws IllegalArgumentException {Objects. requireNonNull (h); final Class <?> [] Intfs = interfaces. clone (); final SecurityManager sm = System. getSecurityManager (); if (sm! = Null) {checkProxyAccess (Reflection. getCallerClass (), loader, intfs);}/** Look up or generate the designated proxy class. */Class <?> Cl = getProxyClass0 (loader, intfs);/** Invoke its constructor with the designated invocation handler. */try {if (sm! = Null) {checkNewProxyPermission (Reflection. getCallerClass (), cl);} final Constructor <?> Cons = cl. getConstructor (constructorParams); final InvocationHandler ih = h; if (! Modifier. isPublic (cl. getModifiers () {AccessController. doPrivileged (new PrivilegedAction <Void> () {public Void run () {cons. setAccessible (true); return null ;}}) ;}return cons. newInstance (new Object [] {h});} catch (IllegalAccessException | InstantiationException e) {throw new InternalError (e. toString (), e);} catch (InvocationTargetException e) {Throwable t = e. getCause (); if (t instanceof RuntimeException) {throw (RuntimeException) t;} else {throw new InternalError (t. toString (), t) ;}} catch (NoSuchMethodException e) {throw new InternalError (e. toString (), e );}}View Code

This code is in JDK1.8 and uses some 1.8 syntax. If you do not know much about it, we recommend that you read <java8 in action> first. There are a lot of code. In fact, some security verification and packaging are in progress. The really useful one is the following two sentences: Class <?> Cl = getProxyClass0 (loader, intfs); find or generate a proxy class. Follow in:

/*** Generate a proxy class. Must call the checkProxyAccess method * to perform permission checks before calling this. */private static Class <?> GetProxyClass0 (ClassLoader loader, Class <?>... Interfaces) {if (interfaces. length> 65535) {throw new IllegalArgumentException ("interface limit exceeded");} // If the proxy class defined by the given loader implementing // the given interfaces exists, this will simply return the cached copy; // otherwise, it will create the proxy class via the ProxyClassFactory return proxyClassCache. get (loader, interfaces );}View Code

Yes, that is, get the interface from the cache. Then use return cons. newInstance (new Object [] {h}); this statement wraps the interface with invocationHandler. The specific source code can be followed up, not detailed. We can see that the principle of JDK dynamic proxy is quite clear. Here is a theoretical point:

The problems solved by AOP can often be solved in the proxy mode. In Java Development, dynamic proxy and static proxy are often used, while AOP is a dynamic proxy, because the proxy class is generated at runtime. Generally, the code written in the proxy mode is generated during the compilation period, called static proxy.

 

Introduce my hometown

The following is the time to run the questions: I am from Shandong. He was born in Weifang and grows in Zaozhuang. Weifang has some places of interest and Cultural Celebrities. Zaozhuang also has some celebrities, the hometown of the Yi guerrillas. Yes, but some of them have poor reputation. Especially in our county, the name is "Xue Cheng", which is xue Di, which has been banned by Meng Zijun. So ...... It is a great fool. The Emperor Qianlong passed this place in the south of the Yangtze River and went into the house to discuss water and drink it. The mother-in-law of the family was beaten out. The Emperor Qianlong said angrily: The city is full of evil water, and the people are full of evil water.

 

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.