Core concepts that run through spring

Source: Internet
Author: User
Tags aop bind commit join object object stub throwable

This article mainly contains the whole concept of spring framework.

1.IoC (inversion control) and dependency injection

2. Aspect-oriented programming

1.IoC (inversion control) and dependency injection

Refer to this article: http://www.bccn.net/Article/kfyy/java/jszl/200610/4512.html

With IOC, objects are passively accepting dependent classes instead of taking the initiative to find them. The container actively injects its dependency class into it when it is instantiated. It can be understood that control inversion shifts the initiative of a class to an interface, and dependency injection injects its dependent classes through an XML configuration file when the class is instantiated.

2. Aspect-oriented programming

2.1 An aspect-oriented programming development environment in Eclipse.

2.2 Introduction to aspect-oriented programming

2.3 A simple AOP demo

2.1 Development environment for aspect-oriented programming in eclipse

Windows, install new softwares, add a new website, enter the following update site:http://download.eclipse.org/tools/ajdt/ 36/update, select all options. As shown in figure:

Click Finish, after the installation is complete, restart Eclipse, and then create a new Java project, the following results should appear:

2.2 Aspect-oriented introduction

In object-oriented programming, the main problem is to solve the relationship between a set of phases, and implement code reuse through inherited policies. However, there are problems that OO cannot solve, and when we want to introduce public behavior to objects without class level, OO's thought is not solved, so it introduces aspect-oriented programming.

Aspect-oriented key concepts:

Join point: The advice is relative to this join, at the moment the program executes.

Advice:advice is the execution code for join point, which is the "execution logic" of the facet.

Pointcut: A set of join point's collectively used to indicate where a recommendation is applied.

Introduction: Adds a field or method to an existing Java class.

Before advice: Call before advice before calling join point.

After advice: contrary to before advice.

2.3 Simple examples of AOP programming

2.3.1 implementation of AOP using J2SE dynamic proxies

Client code:

/** * * */package aop.proxy; Import Com.sun.org.apache.bcel.internal.generic.NEW; /** * Traditional implementation, not using the AOP framework * @author JEFFERYXU * * * */public class Businesslogicusage {/** * @param args */public static void Ma In (string[] args) {//TODO auto-generated method stub ibusinesslogic businesslogic = (ibusinesslogic) loggingproxyaspect. Bind (Securityproxyaspect.bind (New Businesslogiccoreconcern ())); Businesslogic.businessmethod1 (); System.out.println (); BUSINESSLOGIC.BUSINESSMETHOD2 (); } }

Businesslogiccoreconcern.java

Package aop.proxy; /** * Traditional approach without using the AOP framework * @author JEFFERYXU * */public class Businesslogiccoreconcern implements Ibusinesslogic {@Overrid e public void BusinessMethod1 () {//TODO auto-generated method stubs DoCoreBusiness1 ();} @Override public void Businessme THOD2 () {//TODO auto-generated Method Stub DoCoreBusiness2 ();}/** * Perform core business 1 */private void DoCoreBusiness1 () {System . OUT.PRINTLN ("DoCoreBusiness1"); }/** * Execution core Business 2 */private void DoCoreBusiness2 () {System.out.println ("DoCoreBusiness2");}}

Ibusinesslogic.java

/** * @author JEFFERYXU * * Package aop.proxy; Public interface Ibusinesslogic {public void businessMethod1 (), public void businessMethod2 ();

Loggingproxyaspect.java

/** * * */package aop.proxy; Import Java.lang.reflect.InvocationHandler; Import Java.lang.reflect.Method; Import Java.lang.reflect.Proxy; Import sun.awt.geom.AreaOp.AddOp; Import sun.util.logging.resources.logging; /** * @author JEFFERYXU * * */public class Loggingproxyaspect implements invocationhandler{private Object proxyobj; @Overr IDE public object invoke (object proxy, Method method, object[] args) throws Throwable {//TODO auto-generated Method stub Beforeadvice (method); Object object = Method.invoke (Proxyobj, args); Afteradvice (method); return object; The public Loggingproxyaspect (object obj) {this.proxyobj = obj;}/** * generates dynamic objects via dynamic proxy * @param object * @return */Public St Atic object Bind (Object object) {Class CLS = Object.getclass (); return Proxy.newproxyinstance (Cls.getclassloader (), CLS. Getinterfaces (), New Loggingproxyaspect (object)); }/** * Pre-processing * @param method */private void Beforeadvice (method method) {logging ("before calling:" + method.getname ()) ; }/** * After call processing * @pAram Method */private void Afteradvice (method method) {logging ("after calling:" + method.getname ());} private void Logging (String str) {System.out.println (str);}}

Securityproxyaspect.java:

/** * * */package aop.proxy; Import Java.lang.reflect.InvocationHandler; Import Java.lang.reflect.Method; Import Java.lang.reflect.Proxy; /** * @author Xuqiang * * */public class Securityproxyaspect implements Invocationhandler {private Object proxyobj;/* (No N-javadoc) * @see Java.lang.reflect.invocationhandler#invoke (java.lang.Object, Java.lang.reflect.Method, java.lang.object[] */@Override public object Invoke (object arg0, method, object[] args) throws Throwable {//TOD O auto-generated Method Stub/** * is only associated to BUSINESSMETHOD1 */if (Method.getname (). Equalsignorecase ("BusinessMethod1")) { Beforeadvice (method); } Object object = Method.invoke (Proxyobj, args); return object; private void Beforeadvice (method) {Dosecuritycheck ();} private void Dosecuritycheck () {System.out.println ("doi ng security Check "); }/** * @param args */public static void main (string[] args) {//TODO auto-generated method stubs} public Securityproxya SPECT (Object obj) {this.proxyobj = obj;}/** * Generate an object proxy from a dynamic proxy * The @param object * @return */public static object Bind (Object object) {Class CLS = Object.getclass (); re Turn proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), New Securityproxyaspect (object)); } }

The above code is implemented using Invocationhandler in Java. Simply speaking: the proxy class design uses the design idea of the agent pattern, the proxy class object implements all interfaces of the proxy target, and replaces the target object for the actual operation. But this substitution is not a simple substitution, it makes no sense, the purpose of the agent is to enhance the target object method, the essence of this enhancement is usually to intercept the target object's methods. Therefore, a proxy should include a method interceptor that indicates what to do when a method call is intercepted. The Invocationhandler is the interface of the Interceptor. (http://blog.csdn.net/pizishuai2008/archive/2009/07/28/4385906.aspx).

That is, when an implementation class of an interface or a function in an interface invokes an interface, Java automatically calls the Invoke function (a function to be implemented in the Invocationhandler interface). By default, invoking any one of the functions in the interface triggers the Invoke function to be called, but it can be restricted by the name of the method in the function invoke, as in the preceding procedure:

if (Method.getname (). Equalsignorecase ("BusinessMethod1")) {Beforeadvice (method);}

Here is an example of a simple implementation using the Invocationhandler:

Ianimal.java:

Package proxytest; public interface IAnimal {void info ();}

Dog.java:

Package proxytest; public class Dog implements IAnimal {publicly void info () {System.out.println ("This is a dog!");}}

Client program:

Package proxytest; Import java.lang.reflect.*; public class Proxytest {public static void main (string[] args) throws Interruptedexception {final IAnimal animal = new D OG (); Object proxyobj =proxy.newproxyinstance (Animal.getclass (). getClassLoader (), Animal.getclass (). GetInterfaces (),/** * Defines the method called when the Proxyobj object calls the interface interface */New Invocationhandler () {public object Invoke (object proxy, method, Obje Ct[] args) {try {System.out.println ("intercepted method:" + method.getname ()); Return Method.invoke (animal, args); } catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace (); return null;} catch (Illeg Alaccessexception e) {//TODO auto-generated catch block E.printstacktrace (); return null;} catch (Invocationtargetexcep tion e) {//TODO auto-generated catch block E.printstacktrace (); return null;}} }); if (proxyobj instanceof ianimal) {System.out.println ("The Proxyobj is an animal!");} else {System.out.println ("the Proxy OBJ isn ' t an animal! ");} IfProxyobj instanceof Dog) {System.out.println ("The Proxyobj is a dog!");} else {System.out.println ("The proxyobj isn ' t a Dog! ");} IAnimal animalproxy = (ianimal) proxyobj; Animalproxy.info (); Animalproxy.hashcode (); System.out.println (Animalproxy.getclass (). GetName (). toString ()); } }

2.3.2 uses ASPECTJ to achieve the above demo as follows:

Client program:

/** * * */package AOP.ASPECTJ; Import aop.proxy.*; /** * @author JEFFERYXU * * */public class Businesslogicusage {/** * @param args */public static void main (string[] args) {//TODO auto-generated method stub ibusinesslogic businesslogic = new Businesslogiccoreconcern (); businesslogic.busines SMethod1 (); System.out.println (); BUSINESSLOGIC.BUSINESSMETHOD2 (); } }

Securityaspect.java: Add a new aspect

The code is as follows:

/** * * */package AOP.ASPECTJ; Import aop.proxy.*; /** * @author JEFFERYXU * */public aspect Securityaspect {private pointcut securityexecution (): Execution (public void IB Usinesslogic.businessmethod1 ()); Declares a join point, defines when to call the function before and after//declaration before advice before (): Securityexecution () {Dosecuritycheck ();} private Voi D Dosecuritycheck () {System.out.println ("Doing security check");}}

Transcationaspect.java:

/** * * */package AOP.ASPECTJ; Import aop.proxy.*; /** * @author Xuqiang * */public aspect Transcationaspect {/** * define Pointcuts */private Pointcut transcationexecution (): Exec Ution (public void Ibusinesslogic.businessmethod1 ()) | | Execution (public void ibusinesslogic.businessmethod2 ()); /** * Definition before advice */before (): Transcationexecution () {Start ();}; /** * Definition after advice */after (): Transcationexecution () {commit ()}/** * Analog transacation */private void Start () {Syst Em.out.println ("transcation start"); } private void Commit () {System.out.println ("transcation commit");}}

Add the AspectJ attribute to the entire project:

Run the whole project and finish.

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.