Spring AOP Two configuration methods (1)

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

Package Com.bjsxt.model;

public class User {
Private String username;
private String password;
Public String GetUserName () {
return username;
}
public void Setusername (String username) {
This.username = Username;
}
Public String GetPassword () {
return password;
}
public void SetPassword (String password) {
This.password = password;
}
}


/**
* Interface Class
*/
Package Com.bjsxt.dao;
Import Com.bjsxt.model.User;

Public interface Userdao {
public void Save (user user);
}


Implementation interface: Package Com.bjsxt.dao.impl;


Import org.springframework.stereotype.Component;

Import Com.bjsxt.dao.UserDAO;
Import Com.bjsxt.model.User;

@Component ("U")
public class Userdaoimpl implements Userdao {

public void Save (user user) {

System.out.println ("User save11d!");
/*throw New RuntimeException ("exception"); *///Throw exception
}

}

Operation class:

Package com.bjsxt.service;
Import Javax.annotation.Resource;

Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import org.springframework.stereotype.Component;

Import Com.bjsxt.dao.UserDAO;
Import Com.bjsxt.model.User;


@Component ("UserService")
public class UserService {

Private Userdao Userdao;

public void init () {
System.out.println ("Init");
}

public void Add (user user) {
Userdao.save (user);
}
Public Userdao Getuserdao () {
return Userdao;
}
  
@Resource (name= "U")
public void Setuserdao (Userdao Userdao) {
This.userdao = Userdao;
}

public void Destroy () {
System.out.println ("destroy");
}
}


Join AOP

Package COM.BJSXT.AOP;

Import Org.aspectj.lang.annotation.After;
Import org.aspectj.lang.annotation.AfterReturning;
Import org.aspectj.lang.annotation.AfterThrowing;
Import Org.aspectj.lang.annotation.Aspect;
Import Org.aspectj.lang.annotation.Before;
Import Org.aspectj.lang.annotation.Pointcut;
Import org.springframework.stereotype.Component;

@Aspect
@Component
public class Loginterceptor {
@Pointcut ("Execution (public * com.bjsxt.service). *.add (..)) ")
public void MyMethod () {};

/* @Before ("Execution (public void Com.bjsxt.dao.impl.UserDAOImpl.save (Com.bjsxt.model.User))") */
@Before ("MyMethod ()")
public void before () {
System.out.println ("Method Staet");
}
@After ("MyMethod ()")
public void after () {
System.out.println ("method after");
}
@AfterReturning ("Execution (public * Com.bjsxt.dao). *.*(..))")
public void afterreturning () {
System.out.println ("Method afterreturning");
}
@AfterThrowing ("Execution (public * Com.bjsxt.dao). *.*(..))")
public void afterthrowing () {
System.out.println ("Method afterthrowing");
}
}


Configuration file

<?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: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 lines--

<context:annotation-config/>
<context:component-scan base-package= "Com.bjsxt"/> <!--auto-scan
<aop:aspectj-autoproxy/> <!--to add the bank--
</beans>
Test class:

Package com.bjsxt.service;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import Com.bjsxt.model.User;

Dependency Injection
Inverse of Control
public class Userservicetest {

@Test
public void Testadd () throws Exception {
Classpathxmlapplicationcontext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");


UserService service = (userservice) ctx.getbean ("UserService");
System.out.println (Service.getclass ());
Service.add (New User ());
System.out.println ("# # #");

Ctx.destroy ();

}

}
Results:

Class com.bjsxt.service.userservice$ $EnhancerByCGLIB $$7b201784
Method Staet
User save11d!
Method afterreturning
Method 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"?>
<beans xmlns= "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 lines--

<context:annotation-config/>
<context:component-scan base-package= "COM.BJSXT"/>
<bean id= "Loginterceptor" class= "Com.bjsxt.aop.LogInterceptor" ></bean>
<aop:config>
<aop:pointcut expression= "Execution (public * com.bjsxt.service. *.add (..)) "
Id= "Servicepointcut"/>
<aop:aspect id= "Logaspect" ref= "Loginterceptor" >
<aop:before method= "Before" pointcut-ref= "Servicepointcut"/>
</aop:aspect>

</aop:config>
</beans>


The following <beans> is a spring configuration tag that beans 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.

Spring AOP Two configuration methods (1)

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.