Spring framework study Note 5: SpringAOP example, springspringaop

Source: Internet
Author: User

Spring framework study Note 5: SpringAOP example, springspringaop

1. Import package:

Import the two packages in spring

 

Import other packages (download them online ):

 

2. Prepare the target object:

Package service; public class UserServiceImpl implements UserService {@ Override public void save () {System. out. println ("save User! ") ;}@ Override public void delete () {System. out. println (" delete a user! ") ;}@ Override public void update () {System. out. println (" update user! ") ;}@ Override public void find () {System. out. println (" find a user! ");}}
View Code

 

3. Preparation notice:

Package springaop; import org. aspectj. lang. proceedingJoinPoint; // notification class public class MyAdvice {// pre-notification // |-call the method before running // post-notification (if an exception occurs, it will not be called) // |-called after the target method is run // surround notification // |-called before and after the target method // exception interception notification // |-if an exception occurs, the post-notification will be called. // The post-notification will be called no matter whether an exception occurs or not. // |-call the post-notification after the target method is run. // the pre-notification public void before () {System. out. println ("this is a pre-notification !! ");} // Post notification public void afterReturning () {System. out. println (" this is post notification (if an exception occurs, it will not be called )!! ");} // The surround notification public Object around (ProceedingJoinPoint pjp) throws Throwable {System. out. println (" This is part before the surround notification !! "); Object proceed = pjp. proceed (); // call the target method System. out. println (" This is part after the notification !! "); Return proceed;} // public void afterException () {System. out. println (" an exception occurred! ");} // Post-Notification public void after () {System. out. println (" this is post-notification (it will be called if an exception occurs )! ");}}

 

 

4. Configure to weave notifications into the target object

(Import aop constraints)

 

User object of the bean package:

Package bean; import javax. annotation. postConstruct; import javax. annotation. preDestroy; import javax. annotation. resource; import org. junit. validator. publicClassValidator; import org. springframework. beans. factory. annotation. autowired; import org. springframework. beans. factory. annotation. qualifier; import org. springframework. beans. factory. annotation. value; import org. springframework. context. annotation. scope; import org. springframework. stereotype. component; import org. springframework. stereotype. controller; import org. springframework. stereotype. repository; import org. springframework. stereotype. service; // the content of the configuration file <bean name = "user" class = "bean. user "/> // @ Component (" user ") // The four types are essentially the same. To facilitate understanding, we recommend that you use the following three types of // @ Service (" user ") // use the service layer // @ Controller ("user") // use the web layer @ Repository ("user ") // use the dao layer // specify the Scope of action of the object @ Scope (scopeName = "singleton") public class User {@ Value ("Tom") // assign a Value to private String name; private Integer age; // @ Autowired // object assignment, automatic assembly // problem: if multiple objects of the same type are involved, @ Resource (name = "car") cannot be distinguished ") // this method can explicitly specify (recommended) private Car; public car getCar () {return Car;} public void setCar (car Car) {this. car = car;} public String getName () {return name;} public void setName (String name) {this. name = name;} public Integer getAge () {return age;} @ Value ("20") // you can assign a Value in the set method. The effect is the same, but does not destroy encapsulation public void setAge (Integer age) {this. age = age ;}@ Override public String toString () {return "User [name =" + name + ", age =" + age + ", car = "+ car +"] ";}@ PostConstruct // initialization method when the init-mothod public void init () {System. out. println ("initialization") ;}@ PreDestroy // destroy method public void destory () {System. out. println ("Destroy ");}}

 

 

 

Xml configuration file:

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/conte Xt http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd "> <! -- Preparations: import the aop (constraint) namespace --> <! -- 1. Configure the target object --> <bean name = "userService" class = "service. UserServiceImpl"> </bean> <! -- 2. Configure the notification object --> <bean name = "myAdvice" class = "springaop. MyAdvice"> </bean> <! -- 3. Configure to route notifications to the target object --> <aop: config> <! -- Configure the entry point public void service. userServiceImpl. the cut point of save () is the void service of the save () method. userServiceImpl. save () public can omit * service. userServiceImpl. the save () return value is not required. You can * replace * service. userServiceImpl. * () indicates all null parameters of a certain type. * service. * ServiceImpl. *(..) final form: Find all the methods of the class ending with serviceimpl from a package * service .. * ServiceImpl. *(..) --> <aop: pointcut expression = "execution (* service. * ServiceImpl. *(..)) "id =" pc "/> <aop: aspect ref =" myAdvice "> <! -- Specify the before method as the pre-notification --> <aop: before method = "before" pointcut-ref = "pc"/> <! -- Post --> <aop: after-returning method = "afterReturning" pointcut-ref = "pc"/> <! -- Surround notification --> <aop: around method = "around" pointcut-ref = "pc"/> <! -- Exception interception notification --> <aop: after-throwing method = "afterException" pointcut-ref = "pc"/> <! -- Post --> <aop: after method = "after" pointcut-ref = "pc"/> </aop: aspect> </aop: config> </beans>

 

 

Test class:

package springaop;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import bean.User;import service.UserService;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:springaop/applicationContext.xml")public class Demo {    @Resource(name="userService")    private UserService us;        @Test    public void fun1(){        us.save();    }    }

 

 

Call the sava method: the console prints the following

 

 

 

 

Supplement ):

You do not need to use the xml configuration file.

Package annotationaop; import org. aspectj. lang. proceedingJoinPoint; import org. aspectj. lang. annotation. after; import org. aspectj. lang. annotation. afterReturning; import org. aspectj. lang. annotation. afterThrowing; import org. aspectj. lang. annotation. around; import org. aspectj. lang. annotation. aspect; import org. aspectj. lang. annotation. before; import org. aspectj. lang. annotation. pointcut; // notification class @ Aspect // indicates that this class is a notification class p Ublic class MyAdvice {@ Pointcut ("execution (* service. * ServiceImpl. *(..)) ") public void pc () {}// pre-notification // specifies that this method is a pre-notification and specifies the entry point @ Before (" MyAdvice. pc () ") public void before () {System. out. println ("this is a pre-notification !! ");} // Post notification @ AfterReturning (" MyAdvice. pc () ") public void afterReturning () {System. out. println ("this is a post-notification (it will not be called if an exception occurs )!! ");} // Surround notification @ Around (" MyAdvice. pc () ") public Object around und (ProceedingJoinPoint pjp) throws Throwable {System. out. println ("This is part before the notification !! "); Object proceed = pjp. proceed (); // call the target method System. out. println (" This is part after the notification !! "); Return proceed;} // exception notification @ AfterThrowing (" MyAdvice. pc () ") public void afterException () {System. out. println (" exception occurred! ");} // Post notification @ After (" MyAdvice. pc () ") public void after () {System. out. println ("this is a post-notification (it will also be called if an exception occurs )!! ");}}

 

Modify the configuration file:

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/conte Xt http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd "> <! -- Preparations: import the aop (constraint) namespace --> <! -- 1. Configure the target object --> <bean name = "userService" class = "service. UserServiceImpl"> </bean> <! -- 2. Configure the notification object --> <bean name = "myAdvice" class = "annotationaop. MyAdvice"> </bean> <! -- 3. Enable annotation-based weaving --> <aop: aspectj-autoproxy> </beans>

 

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.