Two ways to configure Java Spring AOP

Source: Internet
Author: User
Tags throw exception

First: Annotation configuration AOP

Annotations in Java 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:

  1. User.java

  2. Package Com.bjsxt.model;


  3. public class User {

  4. Private String username;

  5. private String password;

  6. Public String GetUserName () {

  7. return username;

  8. }

  9. public void Setusername (String username) {

  10. This.username = Username;

  11. }

  12. Public String GetPassword () {

  13. return password;

  14. }

  15. public void SetPassword (String password) {

  16. This.password = password;

  17. }

  18. }

  19. /**

  20. * Interface Class

  21. */

  22. Package Com.bjsxt.dao;

  23. Import Com.bjsxt.model.User;


  24. Public interface Userdao {

  25. public void Save (user user);

  26. }

Copy Code

Implementing the interface:

    1. Package Com.bjsxt.dao.impl;


    2. Import org.springframework.stereotype.Component;


    3. Import Com.bjsxt.dao.UserDAO;

    4. Import Com.bjsxt.model.User;


    5. @Component ("U")

    6. public class Userdaoimpl implements Userdao {


    7. public void Save (user user) {


    8. System.out.println ("User save11d!");

    9. /*throw New RuntimeException ("exception"); *///Throw exception

    10. }


    11. }

Copy Code

Operation class:

  1. Package com.bjsxt.service;

  2. Import Javax.annotation.Resource;


  3. Import org.springframework.beans.factory.annotation.Autowired;

  4. Import Org.springframework.beans.factory.annotation.Qualifier;

  5. Import org.springframework.stereotype.Component;


  6. Import Com.bjsxt.dao.UserDAO;

  7. Import Com.bjsxt.model.User;


  8. @Component ("UserService")

  9. public class UserService {


  10. Private Userdao Userdao;


  11. public void init () {

  12. System.out.println ("Init");

  13. }


  14. public void Add (user user) {

  15. Userdao.save (user);

  16. }

  17. Public Userdao Getuserdao () {

  18. return Userdao;

  19. }


  20. @Resource (name= "U")

  21. public void Setuserdao (Userdao Userdao) {

  22. This.userdao = Userdao;

  23. }


  24. public void Destroy () {

  25. System.out.println ("destroy");

  26. }

  27. }

Copy Code

Join AOP

  1. Package COM.BJSXT.AOP;


  2. Import Org.aspectj.lang.annotation.After;

  3. Import org.aspectj.lang.annotation.AfterReturning;

  4. Import org.aspectj.lang.annotation.AfterThrowing;

  5. Import Org.aspectj.lang.annotation.Aspect;

  6. Import Org.aspectj.lang.annotation.Before;

  7. Import Org.aspectj.lang.annotation.Pointcut;

  8. Import org.springframework.stereotype.Component;


  9. @Aspect

  10. @Component

  11. public class Loginterceptor {

  12. @Pointcut ("Execution (public * com.bjsxt.service). *.add (..)) ")

  13. public void MyMethod () {};


  14. /* @Before ("Execution (public void Com.bjsxt.dao.impl.UserDAOImpl.save (Com.bjsxt.model.User))") */

  15. @Before ("MyMethod ()")

  16. public void before () {

  17. System.out.println ("Method Staet");

  18. }

  19. @After ("MyMethod ()")

  20. public void after () {

  21. System.out.println ("method after");

  22. }

  23. @AfterReturning ("Execution (public * Com.bjsxt.dao). *.*(..))")

  24. public void afterreturning () {

  25. System.out.println ("Method afterreturning");

  26. }

  27. @AfterThrowing ("Execution (public * Com.bjsxt.dao). *.*(..))")

  28. public void afterthrowing () {

  29. System.out.println ("Method afterthrowing");

  30. }

  31. }

Copy Code

Configuration file

  1. <?xml version= "1.0" encoding= "UTF-8"?>

  2. <beans xmlns= "Http://www.springframework.org/schema/beans"

  3. Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"

  4. xmlns:context= "Http://www.springframework.org/schema/context"

  5. xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"

  6. Xsi:schemalocation= "Http://www.springframework.org/schema/beans


  7. Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd



  8. Http://www.springframework.org/schema/context



  9. Http://www.springframework.org/schema/context/spring-context-2.5.xsd



  10. Http://www.springframework.org/schema/aop



  11. Http://www.springframework.org/schema/aop/spring-aop-3.1.xsd


  12. ><!--to add the last 2 lines--


  13. <context:annotation-config/>

  14. <context:component-scan base-package= "Com.bjsxt"/> <!--auto-scan

  15. <aop:aspectj-autoproxy/> <!--to add the bank--

  16. </beans>

Copy Code

Test class:

  1. Package com.bjsxt.service;

  2. Import Org.junit.Test;

  3. Import Org.springframework.context.ApplicationContext;

  4. Import Org.springframework.context.support.ClassPathXmlApplicationContext;


  5. Import Com.bjsxt.model.User;


  6. Dependency Injection

  7. Inverse of Control

  8. public class Userservicetest {


  9. @Test

  10. public void Testadd () throws Exception {

  11. Classpathxmlapplicationcontext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");


  12. UserService service = (userservice) ctx.getbean ("UserService");

  13. System.out.println (Service.getclass ());

  14. Service.add (New User ());

  15. System.out.println ("# # #");


  16. Ctx.destroy ();


  17. }


  18. }

Copy Code

Results:

    1. Class com.bjsxt.service.userservice$enhancerbycglib$7b201784

    2. Method Staet

    3. User save11d!

    4. Method afterreturning

    5. Method after

    6. ###

Copy Code

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

  1. <?xml version= "1.0" encoding= "UTF-8"?>

  2. <beans xmlns= "Http://www.springframework.org/schema/beans"

  3. Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"

  4. xmlns:context= "Http://www.springframework.org/schema/context"

  5. xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"

  6. Xsi:schemalocation= "Http://www.springframework.org/schema/beans


  7. Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd



  8. Http://www.springframework.org/schema/context



  9. Http://www.springframework.org/schema/context/spring-context-2.5.xsd



  10. Http://www.springframework.org/schema/aop



  11. Http://www.springframework.org/schema/aop/spring-aop-3.1.xsd


  12. ><!--to add the last 2 lines--


  13. <context:annotation-config/>

  14. <context:component-scan base-package= "COM.BJSXT"/>

  15. <bean id= "Loginterceptor" class= "Com.bjsxt.aop.LogInterceptor" ></bean>

  16. <aop:config>

  17. <aop:pointcut expression= "Execution (public * com.bjsxt.service. *.add (..)) "

  18. Id= "Servicepointcut"/>

  19. <aop:aspect id= "Logaspect" ref= "Loginterceptor" >

  20. <aop:before method= "Before" pointcut-ref= "Servicepointcut"/>

  21. </aop:aspect>


  22. </aop:config>

  23. </beans>

Copy Code

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.


Two ways to configure Java Spring AOP

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.