Quickly and efficiently master the Aspect-Oriented Programming applications of Spring in enterprise-level projects, the interview skills of out-of-band lectures, and the enterprise-level spring

Source: Internet
Author: User

Quickly and efficiently master the Aspect-Oriented Programming applications of Spring in enterprise-level projects, the interview skills of out-of-band lectures, and the enterprise-level spring

Spring object-oriented programming (AOP) is the cornerstone of enterprise-level applications. It can be said that if you want to upgrade to a Senior Programmer, this part of knowledge is essential.

Here we will talk about this part of knowledge with some specific cases, and we will also give some common questions about AOP. The text and cases in this article are adapted based on the java web lightweight development interview tutorial.

 

1. Use Cases for Aspect-Oriented Programming

Now you have the following requirements. After calling many methods in the project, you need to call the memory reclaim method. You can use the following methods to achieve this requirement.

1 void f1 () {2f1 normal business 3 // reclaim memory 4 clearMem (); 5} 6 void f2 () {7f2 normal business 8 // reclaim memory 9 clearMem (); 10}

  

The problem with this implementation method is that we have to write the code for calling the reclaim memory in all necessary methods, which will lead to code duplication. If there are any modifications, You have to modify many of them.

What's worse, we assume that the memory recovery method is maintained by the memory management team, while business teams such as f1 and f2 are responsible for normal maintenance. If the memory management team updates the Code, such as modifying the clearMem method name or changing the parameters, the business team also needs to change the code. As mentioned before, if the project code is to be deployed to the production environment, it usually takes a large cost. It is reasonable for the memory management team to deploy the code, but there is no need to be involved in the business team. In this scenario, the object-oriented programming method cannot help us, and we need to use the Aspect-Oriented Programming Method.

2 Case Study

In a bank project, when we call the method of adding and deducting money to the account, we need to complete some fixed actions, such as recording the flow or security check, you can follow the steps below to use AOP. The team Upgrade Code. For example, if the clearMem method name is modified or the parameters are changed, the business team also needs to change the code. As mentioned before, if the project code is to be deployed to the production environment, it usually takes a large cost. It is reasonable for the memory management team to deploy the code, but there is no need to be involved in the business team. In this scenario, the object-oriented programming method cannot help us, and we need to use the Aspect-Oriented Programming Method.

Step 1: Write account interfaces and implementation classes. Here we still follow the idea of interface-oriented programming. The interface code is Account. java, where two methods are defined in rows 2nd and 3rd.

1public interface  Account{2 void add(int money);3 void minus(int money);4}

The implementation class code is AccountImpl. java. The account name attribute is defined in row 2nd, and its get and set methods are defined in row 3rd and row 6th.

1 public class AccountImpl implements Account {2 private String name; 3 public String getName () {4 return name; 5} 6 public void setName (String name) {7this. name = name; 8} 9 public void add (int money) {10System. out. println ("add money to" + name + "Account" + money + "RMB"); 11} 12 public void minus (int money) {13System. out. println ("deduct money from" + name + "account:" + money + "RMB"); 14} 15}

Step 2: Compile the BeforeAdvice. java class. In the project, you need to call the before method encapsulated in the method before calling the method of money addition and deduction.

1 import java. lang. reflect. method; 2 import org. springframework. aop. methodBeforeAdvice; 3 public class BeforeAdvice implements MethodBeforeAdvice4 {5 public void before (Method m, Object [] args, Object target) throws Throwable6 {7 System. out. println ("before method call"); 8 System. out. println ("execution method:" + m); 9 System. out. println ("the parameter of the method is:" + args [0]); 10 System. out. println ("target object:" + target); 11} 12}

Please note that line 1 requires the MethodBeforeAdvice interface and line 3. You can define the business actions of the pre-operation in the before method. Here we print some information.

Similarly, post operations are defined in AfterAdvice. java. It is similar to the pre-operation. Here, the afterReturning method in the AfterReturningAdvice interface is implemented in row 5th, and some information is printed.

1 import org. springframework. aop. afterReturningAdvice; 2 import java. lang. reflect. method; 3 public class AfterAdvice implements AfterReturningAdvice4 {5 public void afterReturning (Object returnValue, Method m, Object [] args, Object target) throws Throwable6 {7 System. out. println ("after method call"); 8 System. out. println ("execution method:" + m); 9 System. out. println ("the parameter of the method is:" + args [0]); 10 System. out. println ("target object:" + target); 11} 12}

In addition, you can also define the surround operation, the Code is as follows.

1 import org. aopalliance. intercept. methodInterceptor; 2 import org. aopalliance. intercept. methodInvocation; 3 public class AroundInterceptor implements MethodInterceptor4 {5 public Object invoke (MethodInvocation invocation) throws Throwable6 {7 System. out. println ("before calling a method: invocation Object: [" + invocation + "]"); 8 Object rval = invocation. proceed (); 9 System. out. println ("call ends... "); 10 return rval; 11} 12}

Here the MethodInterceptor interface is implemented in line 3rd. Once the invoke method defined in line 5th is called, the Spring container will use the original method (for example, the method of adding or deducting money) the control is handed over to the invoke method. In this method, some operations (such as printing 7th rows) and post operations (such as printing 9th rows) are added, then, the original method is executed through the action of Row 3.

So far, two methods have been defined: the first is the money adding and Deduction Method of the primary account, and the second is the action of the front, back, and circle. As you can see, in this method, there are no businesses that are processed in the frontend and backend mode. They are completely separated. In professional terms, the coupling between them is very low.

Step 3: Use the following code in the Main class.

1 import org. springframework. context. applicationContext; 2 import org. springframework. context. support. fileSystemXmlApplicationContext; 3 public class Main4 {5 public static void main (String [] args) throws Exception6 {7 ApplicationContext ctx = new FileSystemXmlApplicationContext ("src/ApplicationContext. xml "); 8 Account account Account = (Account) ctx. getBean ("account"); 9 System. out. println ("first add method"); 10 account. add (100); 11 System. out. println ("second minus method"); 12 account. minus (100); 13} 14}

In rows 7th and 8th, the instance that loads and obtains the Account is called in rows 10th and 12th.

From the code of the call, there is still no trace of the pre-surround processing, so how are they assembled?

Finally, let's take a look at the configuration file and provide the code for the main part.

1 <beans> 2 <! -- Configure the target object --> 3 <bean id = "accountTarget" class = "AccountImpl"> 4 <! -- Inject the name property value to the target object --> 5 <property name = "name"> 6 <value> Java </value> 7 </property> 8 </bean>

In row 3rd, the Bean accountTarget is defined, and from row 5th to row 7th, the initialization value of name is set to Java.

9 <! -- The First processing class --> 10 <bean id = "myAdvice" class = "BeforeAdvice"/> 11 <! -- The second processing class --> 12 <bean id = "myAroundInterceptor" class = "AroundInterceptor"/> 13 <! -- Specifies which methods to add processing --> 14 <bean id = "addAdvisor" class = "org. springframework. aop. support. RegexpMethodPointcutAdvisor"> 15 <! -- Advice attribute determination processing bean --> 16 <property name = "advice"> 17 <! -- The processing bean definition here uses nested beans. You can also reference another bean of the container --> 18 <bean class = "AfterAdvice"/> 19 </property> 20 <! -- Determine the regular expression mode --> 21 <property name = "patterns"> 22 <list> 23 <! -- Confirm the regular expression list --> 24 <value>. * add *. </value> 25 </list> 26 </property> 27 </bean>

From rows 9th to 27th, three Bean processing classes are defined. The first two are simple, but they only use the pre-processing class and the surround processing class. For the third post-processing class, we wrap the Bean AfterAdvice defined in row 18th into the Bean addAdvisor of row 14th to row 27th. At the same time, the interceptor can only be used in the add method by specifying rows 21st and 24th, but it has no effect on other methods.

28 <! -- Use ProxyFactoryBean to generate a proxy object --> 29 <bean id = "account" class = "org. springframework. aop. framework. ProxyFactoryBean"> 30 <! -- Interface implemented by the proxy object --> 31 <property name = "proxyInterfaces"> 32 <value> Account </value> 33 </property> 34 <! -- Set the target object --> 35 <property name = "target"> 36 <ref local = "accountTarget"/> 37 </property> 38 <! -- Interceptor Used by the proxy object --> 39 <property name = "interceptorNames"> 40 <list> 41 <value> runAdvisor </value> 42 <value> myAdvice </value> 43 <value> myAroundInterceptor </value> 44 </list> 45 </property> 46 </bean> 47 </beans>

The pre-and post-surround processing defined is applied to the add and minus methods of the Accout class, and is embodied in the Bean of accounts from rows 29th to rows 46th, rows 41st to 43rd specify the three processing classes defined above.

When you run the Main class, the following output is displayed.

1 first add method 2 This is the output before calling the add method in the Main Class 3 before calling the method 4 before calling the add method, the method for calling before Method 5 defined in BeforeAdvice is: public abstract void Account. the parameter of the add (int) 6 method is: 1007 the target object is: AccountImpl @ 11d5b598 from row 3rd to row 5th is the output of the before method, from which we can see that the execution method is add, the parameter is 100, and the target object is before AccountImpl9 calls the method. Invocation object: [ReflectiveMethodInvocation: public abstract void Account. add (int); target is of class [AccountImpl] 10. This is the invocation for the Surround Operation of the add method. proceed () before the output 11 to the Java account to add 100 yuan 12 this is a normal money adding operation 13 call ended... 14. This is the invocation for the Surround Operation of the add method. output 15 after proceed () is 16 after method call. This is to call the afterReturning method in AfterAdivce. 17. The execution method is: public abstract void Account. the parameter of the add (int) 18 method is: 10019. The target object is: accountImpl @ 11d5b5920 from 10th rows to 12th rows is the output of afterReturning 21 the second minus Method 22 This is the output of calling the minus method in the Main Class 23 before the method call 24 is also in minus before calling the method, the method for calling before Method 25 defined in BeforeAdvice is: public abstract void Account. the parameter of minus (int) 26 method is: 10027 the target object is: AccountImpl @ 11d5b5928 from 15th rows to 17th rows, and the output in before method is also seen. 29. Invocation object: [ReflectiveMethodInvocation: public abstract void Account. minus (int); target is of class [AccountImpl] 30. This is the invocation for the minus method Surround Operation. output 31 before proceed () deduction from Java account: 100 RMB 32 output when calling minus Method 33 call ended... 34. This is the invocation for the Surround Operation of the add method. the output 35 before proceed () is in the configuration file. Because the AfterAdvice class only applies to the add method, it will not be executed after the minus method.

3. Interview points

In actual use, you do not need to know too much about the concept, but should master the following knowledge points:

① What types of notifications are there?

② How do you use AOP in combination with projects?

③ If the pre-notification only applies to some methods and does not apply to all methods, what should I do?

We can also use annotations (rather than configuration files) to implement cross-section programming. The limitations of this practice have been mentioned above, so we will not go into detail here.

4. How to prove that you have mastered basic Spring skills during the interview?

We often use Spring's Web development skills, other components (such as Hibernate) Integration skills, database transactions, and other skills. As the basis of Spring, IoC and AOP are frequently used.

For these basic skills, we generally do not ask about concepts, because it cannot be differentiated (just learning but not having business project experience) and proficient (working for about three years is becoming a Senior Programmer).

First, we will check the candidate's comprehensive understanding of Spring. In general, we hope that the candidate can reflect the advantages of Spring based on the actual project, for example, we can tell you how to implement features such as free assembly of interfaces and reduced coupling in their projects, or what specific benefits they bring to their projects. Here we are very concerned about the integration of projects, because this is a necessary condition for determining whether a candidate has used Spring and is proficient in Spring.

Secondly, since the candidates have implemented many Spring projects, we can talk about some detours and experiences when using Spring in the project development process. Many of the answers we have heard will cause problems for project maintenance when using annotations, or some problems for calling between multiple threads when using a single instance to create beans.

In this regard, we generally do not stick to the answer itself, even as long as we don't get too wrong, we focus on the degree of familiarity with Spring candidates, to measure their experience in Spring.

Finally, we will ask questions about Bean lifecycle and source code in Spring. This part is indeed a relatively senior content. For programmers who are about to upgrade within three years of working experience, our expectation is to be able to know the Bean lifecycle. When there are some requirements, know which node methods are called for implementation. As for the source code for implementing IoC and AOP in the Spring kernel, this is a requirement for senior programmers (about five years of working experience). If Junior programmers can answer this question, it is a plus.

Next we will summarize the frequently asked questions. Please check the learning situation of this chapter based on these questions.

First, read the resume and find that the candidate will ask him to explain how to use IoC based on the actual project.

The technical points of IoC itself are not hard to describe, but remember to combine them with specific projects, for example, in a bank project, a management account class can dynamically load another class to manage security risks through IoC features, which can reduce coupling.

Second, describe the types of autowired you have used in conjunction with the project.

Third, describe the annotations you have used.

@ Autowired and other annotations are not difficult to describe, but here you can also talk about the disadvantages of using annotations. This shows that you have done a lot of Spring projects.

Fourth, first ask how to implement singleton and how to implement multiple examples. Then ask the candidate to explain in combination with the project under which circumstances the Bean should be created in singleton mode (or multiple examples.

First, you need to understand the syntax for setting a singleton. Then, you need to understand the concepts and usage of stateful and stateless beans. Finally, you need to explain how to create them. The answer here is to confirm the creation of the use case as needed.

Fifth, let's talk about the Bean lifecycle and the methods you have rewritten. You can also ask, what should I do if I want to number the Bean? Or how to set the Spring initialization method. In short, when you understand the nodes in the Spring life cycle and meet actual requirements, you will be able to clearly understand which methods to rewrite.

Familiarize yourself with the lifecycle of Spring Bean and the methods of each node.

Sixth, how do you use AOP in the project? Most candidates say that using AOP for log printing is indeed a very suitable use.

Here, you can also describe it based on the actual project.

7. Let's talk about the specific AOP you have used in your project, such as the front, back, and circle.

This is actually a popular saying. The more professional question is the type of AOP notifications you have used. We know that there are a total of five types of notification for AOP. In a project, the more you use the better, the better, but the more suitable it is to be used, even if your project uses the front-end, but that's enough. We have seen some people say that five of them have been used, but they are not correct. This may be a perfect addition to painting.

 

 

 

Related Article

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.