SSH deep adventure (11) AOP principles and related concepts + xml configuration instances (comparison of the advantages and disadvantages of annotation methods)

Source: Internet
Author: User

Next

SSH deep adventure (10) AOP principles and related concepts learning + aspectj annotation configuration Spring AOP. In this article, we mainly learn how to use configuration XML to implement AOP.


This document uses the forced cglb proxy method


The securityhandler notification class can be changed to Security Detection and log management.


<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">package com.bjpowernode.spring;import org.aspectj.lang.JoinPoint;public class SecurityHandler {private void checkSecurity(JoinPoint joinPoint) {for (int i=0; i<joinPoint.getArgs().length; i++) {System.out.println(joinPoint.getArgs()[i]);}System.out.println(joinPoint.getSignature().getName());System.out.println("-------checkSecurity-------");}}</span></span></span>


Usermanager Interface


<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">package com.bjpowernode.spring;public interface UserManager {public void addUser(String username, String password);public void delUser(int userId);public String findUserById(int userId);public void modifyUser(int userId, String username, String password);}</span></span></span>

Implementation of the usermanagerimpl Interface
<Span style = "font-size: 18px;"> <span style = "font-size: 18px;"> <span style = "font-size: 18px; "> package COM. bjpowernode. spring; public class usermanagerimpl implements usermanager {public void adduser (string username, string password) {// checksecurity (); system. out. println ("--------- usermanagerimpl. add () -------- ");} public void deluser (INT userid) {// checksecurity (); system. out. println ("--------- usermanagerimpl. deluser () -------- ");} Public String finduserbyid (INT userid) {// checksecurity (); system. out. println ("--------- usermanagerimpl. finduserbyid () -------- "); Return" Zhang San ";} public void modifyuser (INT userid, string username, string password) {// checksecurity (); system. out. println ("--------- usermanagerimpl. modifyuser () -------- ");} // Private void checksecurity () {// system. out. println ("------- checksecurity -------"); // }}</span> </span>

Configure applicationcontext. XML (<! -- Force cglib proxy -->)


<Span style = "font-size: 18px;"> <span style = "font-size: 18px;"> <span style = "font-size: 18px; "> <? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: AOP = "http://www.springframework.org/schema/aop" xmlns: Tx = "http://www.springframework.org/schema/tx" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http: // www. Springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd "> <! -- Force cglib proxy --> <! -- <AOP: aspectj-autoproxy proxy-target-class = "true"/> --> <bean id = "usermanager" class = "com. bjpowernode. spring. usermanagerimpl "/> <bean id =" securityhandler "class =" com. bjpowernode. spring. securityhandler "/> <AOP: config> <AOP: aspect id =" securityaspect "ref =" securityhandler "> <! -- Method starting with add <AOP: pointcut id = "addaddmethod" expression = "execution (* Add * (...)"/> --> <! -- Com. bjpowernode. all methods of all classes in the spring package <AOP: pointcut id = "addaddmethod" expression = "execution (* COM. bjpowernode. spring. *. *(..)) "/> --> <AOP: pointcut id =" addaddmethod "expression =" execution (* COM. bjpowernode. spring. *. add *(..)) | execution (* COM. bjpowernode. spring. *. del *(..)) "/> <AOP: Before method =" checksecurity "pointcut-ref =" addaddmethod "/> </AOP: aspect> </AOP: config> </beans> </span>

Client client call


<Span style = "font-size: 18px;"> <span style = "font-size: 18px;"> <span style = "font-size: 18px; "> package COM. bjpowernode. spring; import Org. springframework. beans. factory. beanfactory; import Org. springframework. context. support. classpathxmlapplicationcontext; public class client {public static void main (string [] ARGs) {beanfactory factory = new classpathxmlapplicationcontext ("applicationcontext. XML "); usermanagerimpl usermanager = (usermanagerimpl) factory. getbean ("usermanager"); usermanager. adduser ("Zhang San", "123") ;}</span> </span>

Final Effect




Differences between the two proxies of AOP

JDK interface-based implementation: JDK dynamic proxy acts as a proxy for classes that implement interfaces.

  • Cglib is based on inheritance: cglib proxy can generate a subclass for the specified class. Because it is an inheritance, it is best not to use Final Declaration for the target class.
  • If the target object implements the interface, the dynamic proxy of JDK is used by default to implement AOP. You can also use cglb to generate a proxy;
  • If the target object does not implement the interface, you must introduce cglb. Spring will switch between the dynamic proxy of JDK and the cglb proxy.

In general, JDK proxy is encouraged, because services generally abstract an interface without introducing new things. If it is a legacy system that has not previously implemented interfaces, you can only use cglib.

In general, JDK dynamic proxy is preferred. Although its efficiency does not seem to be comparable to that of cglib proxy, its objects can be released normally after they are used up. However, cglib proxy produces a new class for each proxy object. Once a class is loaded into JVM, the memory occupied by these new classes will not be released according to most JVM mechanisms. J2EE generally runs for a long period of time, causing some pressure on the memory.


Comparison of advantages and disadvantages of XML and aspectj annotation Configuration


In XML format, all the section, cut point, notification, and other configurations are written in one or several spring configuration files. The advantage is that, from the configuration file, you can clearly see what aspects of the system are, the notification (advice) and the notification (advice) used in a specific aspect) the cut point of the function. In the aspectj style, the mark section in the Java program is messy and fuzzy.


Under what circumstances does annotation-based AOP work? Or what are the advantages of using annotations to implement AOP?

1. XML-style AOP only supports "Singleton" slice instance model, while aspectj-style AOP
There is no such restriction.

2. XML-style AOP does not support the declaration of naming connection points, whereas aspectj-style AOP does not have this restriction. For more information, see the following instance code:
In the @ aspectj style, we can write the following content:



<span style="font-size:18px;">    @Pointcut(execution(* get*()))                      public void propertyAccess() {}                                            @Pointcut(execution(org.xyz.Account+ *(..))                      public void operationReturningAnAccount() {}                                            @Pointcut(propertyAccess() && operationReturningAnAccount())                  public void accountPropertyAccess() {}  </span>

In the XML style, we cannot use the '&' character to connect to the named connection point, as shown below:


<Span style = "font-size: 18px;"> <AOP: pointcut id = "propertyaccess" expression = "execution (* Get * ()"/> <AOP: pointcut id = "operationreturninganaccount" expression = "execution (Org. XYZ. account + *(..)) "/> <! -- Incorrect configuration --> <AOP: pointcut id = "accountpropertyaccess" expression = "propertyaccess & operationreturninganaccount"/> </span>

Note: Although XML-style AOP does not support the declaration of naming connection points, it can be processed in the following form:


<span style="font-size:18px;">    <aop:pointcut id="propertyAccess"                      expression="execution(* get*())"/>         <aop:pointcut id="operationReturningAnAccount"                  expression="execution(org.xyz.Account+ *(..))"/>          <aop:pointcut id="accountPropertyAccess"                  expression="execution(* get*()) and execution(org.xyz.Account+ *(..))"/>  </span>


Summary

Both methods have implemented AOP, which improves the Reuse Rate of program code and reflects the benefits of abstraction. The two complement each other and draw lessons from each other, we select and make appropriate decisions based on the actual situation, and the process suitable for development in the system development environment is the most important,

In practice, let's get a deeper understanding of ing

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.