Java Framework---Spring AOP two ways to configure

Source: Internet
Author: User
Tags throw exception

First: Annotation configuration AOP

Annotation configuration AOP (implemented using the AspectJ class library) is broadly divided into three steps:
1. Use annotation @aspect to define a facet, define the Pointcut (@Pointcut) in the slice, the notification type (@Before, @AfterReturning, @After, @AfterThrowing, @Around).
2. Develop classes that need to be intercepted.
3. Configure the facets into XML, of course, we can also use the way the bean is automatically scanned. In this case, it is managed by the Spring AOP container.

Also need to reference the jar package of AspectJ: Aspectjweaver.jar Aspectjrt.jar

Instance:

User.java
 PackageCom.bjsxt.model; Public classUser {PrivateString username; PrivateString password;  PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}
/**
* Interface Class
*/
package Com.bjsxt.dao; Import Com.bjsxt.model.User; Public Interface Userdao { publicvoid Save (user user);}

Implementing the interface:

 PackageCom.bjsxt.dao.impl;Importorg.springframework.stereotype.Component;ImportCom.bjsxt.dao.UserDAO;ImportCom.bjsxt.model.User; @Component ("U") Public classUserdaoimplImplementsUserdao { Public voidSave (User user) {System.out.println ("User save11d!"); /*throw new RuntimeException ("exception");*/ //Throw Exception    }}

Operation class:

 PackageCom.bjsxt.service;ImportJavax.annotation.Resource;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Qualifier;Importorg.springframework.stereotype.Component;ImportCom.bjsxt.dao.UserDAO;ImportCom.bjsxt.model.User; @Component ("UserService") Public classUserService {PrivateUserdao Userdao;  Public voidinit () {System.out.println ("Init"); }         Public voidAdd (user user) {userdao.save (user); }     PublicUserdao Getuserdao () {returnUserdao; } @Resource (Name= "U")     Public voidSetuserdao (Userdao Userdao) { This. Userdao =Userdao; }        Public voiddestroy () {System.out.println ("Destroy"); }}

Join AOP

 PackageCOM.BJSXT.AOP;ImportOrg.aspectj.lang.annotation.After;Importorg.aspectj.lang.annotation.AfterReturning;Importorg.aspectj.lang.annotation.AfterThrowing;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before;ImportOrg.aspectj.lang.annotation.Pointcut;Importorg.springframework.stereotype.Component, @Aspect @component Public classloginterceptor {@Pointcut ("Execution (Public * com.bjsxt.service). *.add (..)) ")     Public voidMyMethod () {}; /*@Before ("Execution (public void Com.bjsxt.dao.impl.UserDAOImpl.save (Com.bjsxt.model.User))")*/@Before ("MyMethod ()")     Public voidbefore () {System.out.println ("Method Staet"); } @After ("MyMethod ()")     Public voidAfter () {System.out.println ("Method After"); } @AfterReturning ("Execution (Public * Com.bjsxt.dao). *.*(..))")     Public voidafterreturning () {System.out.println ("Method Afterreturning"); } @AfterThrowing ("Execution (Public * Com.bjsxt.dao). *.*(..))")     Public voidafterthrowing () {System.out.println ("Method Afterthrowing"); } }

Configuration file

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"    xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5. XSD Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring -context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/ Schema/aop/spring-aop-3.1.xsd "><!--to add the last 2 rows -               <Context:annotation-config/>    <Context:component-scanBase-package= "COM.BJSXT"/>  <!--Automatic Scanning -    <Aop:aspectj-autoproxy/>  <!--to add a bank -</Beans>

Test class:

 PackageCom.bjsxt.service;Importorg.junit.Test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportCom.bjsxt.model.User;//Dependency Injection//Inverse of Control Public classuserservicetest {@Test Public voidTestadd ()throwsException {classpathxmlapplicationcontext ctx=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); UserService Service= (UserService) ctx.getbean ("UserService");        System.out.println (Service.getclass ()); Service.add (NewUser ()); System.out.println ("###");            Ctx.destroy (); }}

Results:

class com.bjsxt.service.userservice$ $EnhancerByCGLIB $$7b201784method staetuser save11d! Method Afterreturningmethod after###

Attention:

    • @Aspect: It means that this class is a tangent class
    • @Componet: Because it requires spring to be managed as a slice class, it is necessary to initialize this class to the management of spring when it is initialized;
    • @Befoe: Logic for Pointcuts (Advice)
    • Execution ...: pointcut syntax
Second type: XML configuration AOP

Example ibid: Only the configuration file is different

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5. XSD Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring -context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/ Schema/aop/spring-aop-3.1.xsd "><!--to add the last 2 rows -               <Context:annotation-config/>    <Context:component-scanBase-package= "COM.BJSXT"/>    <BeanID= "Loginterceptor"class= "Com.bjsxt.aop.LogInterceptor"></Bean>    <Aop:config>        <Aop:pointcutexpression= "Execution (public * com.bjsxt.service). *.add (..)) "ID= "Servicepointcut"/>        <Aop:aspectID= "Logaspect"ref= "Loginterceptor">            <Aop:beforeMethod= "Before"Pointcut-ref= "Servicepointcut" />        </Aop:aspect>            </Aop:config></Beans>

The following <beans> is a spring configuration tag thatbeans several important attributes :

xmlns

is the default XML document parsing format, which is the beans of spring. The address is Http://www.springframework.org/schema/beans.

By setting this property, all attributes declared in beans can be used directly through <>, such as <bean> and so on.

Xmlns:xsi:

Is the specification that XML needs to obey, through the URL can see, is the unified specification of W3, behind through xsi:schemalocation to locate all parse file.

XMLNS:AOP:

This is the point, and some of the semantic specifications that we need to use here are related to facet-oriented AOP.

XMLNS:TX:

The transaction-related configuration content in spring.

An XML file that can only declare a specification of the default semantic parsing.

For example, in the XML above only beans one is the default, the others need to be used through a specific tag, such as AOP, it has a lot of properties, if you want to use, the front must be added aop:xxx. Like the aop:config above.

Similarly, if the default xmlns configuration is an AOP-related semantic parsing specification, you can write the config tag directly in XML.

Java Framework---Spring AOP two ways to configure

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.