Spring's first knowledge of IOC&AOP

Source: Internet
Author: User

The role of the spring framework

Spring is a lightweight enterprise-class framework that offers IOC containers, AOP implementations, dao/orm support, Web integration, and more, with the goal of making existing Java EE technologies easier to use and promoting good programming practices.

The spring framework is primarily used to integrate with other technologies (struts,hibernate, etc.) to implement a low-coupling association of bean components in an application. Ultimately, it can improve system expansion and maintainability.

In the future we will use the spring framework to manage the various components of the system (Action,service,dao). Use spring's IOC and AOP mechanisms to implement the association of each component. This enables low-coupling calls. Enhanced system maintainability and extensibility.

Spring Base jar Package

Spring IOC controlled inversion (inversion of control)

control inversion, also known as Dependency injection, is a design concept in object-oriented programming to reduce the coupling between code.

What are the IOC's greatest benefits? Because the object generation is defined in XML, it becomes very simple when we need to change the implementation subclass (generally such objects are implemented on an interface), as long as the XML is modified so that we can even implement hot-swapping of objects (a bit like USB interface and SCSI hard disk).

Cases:

 Public classhellospring {PrivateString who =NULL;  Public voidprint () {System.out.println ("Hello" + This. getwho ()); }     PublicString getwho () {returnWho ; }     Public voidsetwho (String who) { This. who =Who ; }}

Applicationcontext.xml file

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >    <!--Services -    <!--declare an instance of spring that needs to be created through the bean element, the type of the instance is specified by the Class property, and a unique name is given to the instance through the ID property to use in the program -    <BeanID= "Hellospring"class= "Cn.cnsdhzzl.biz.HelloSpring">    <!--The value of the Name property here corresponds to the setwho of the property in the class, and the Value property is assigned the ' Spring ' -        < Propertyname= "Who"value= "Spring">        </ Property>    </Bean>    <!--More beans definitions for services go -</Beans>

Test class:

    @Test    publicvoid  fristspring () {        //  Reads the spring configuration file from the Classpath path, instantiating the spring context        new  Classpathxmlapplicationcontext (                "Applicationcontext.xml");         // using the Getbean method of the context, according to the ID attribute value in the XML file past the Bean instance        hellospring hs = (hellospring) ac.getbean ("hellospring");         // instance Invocation method         hs.print ();    }

Note:

ApplicationContext: is an interface that is responsible for reading the spring configuration file, managing the loading and generation of objects, maintaining the Bean object's dependency on the quality of the Bean object, and responsible for the bean's life cycle.
Classpathxmlapplicationcontext: Yes An implementation class for the ApplicationContext interface that is used to read the spring configuration file from the Classpath path (Filesystemxmlapplicationcontext can also be used to load the spring configuration file).
Depending on the control reversal, the assertion of dependency injection may be easier to understand, that is, the container (such as spring) is responsible for the specific object injection (Assignment) that the component relies on to the component, thus avoiding the hard-coded way in which components are organized together.

Spring Aop (Aspect oriented programming)

In a business system, there are always things that are scattered and penetrated into the system and have to be dealt with, and the operations that are interspersed with the established business are called "crosscutting logic" and Chen Wei's ' facets '

Aspect-oriented programming, simply speaking, is to add new functionality to code snippets without changing the source program, and to enhance the processing of code snippets.

AOP is generally suitable for applications with crosscutting logic, such as cut-in logging, access control, transaction management, and performance detection.

Aopjar Bag

Cases:

Define a DAO and implement

 Public Interface Userentitydao {    publicvoid  Save (userentity user);}

Define a biz and implement

 public  class  Userentitybizimpl Span style= "color: #0000ff;" >implements   userentitybiz { private      Userentitydao DAO; @Override  public  void   Save (userentity user) {dao.save (user);  public   Userentitydao Getdao () {return   DAO;  public  void   Setdao (Userentitydao dao) { 

Creating a predecessor Enhancement class

//Methodbeforeadvice for pre-enhancement Public classLoggerbeforeImplementsMethodbeforeadvice {Private Static FinalLogger Logger = Logger.getlogger (loggerbefore.class); @Override Public voidbefore (method, object[] arguments, Object target)throwsthrowable {logger.info ("+ method.getname () +" method called "+ Target +". "+" Method entry "+arrays.tostring (arguments)); }}

Creating a post-enhanced class

//Post-build enhancements via Afterreturningadvice Public classLoggerafterreturningImplementsAfterreturningadvice {Private Static FinalLogger Logger =Logger. GetLogger (loggerafterreturning.class); @Override Public voidafterreturning (Object ReturnValue, method, object[] arguments, object target)throwsthrowable {logger.info ("+ method.getname () +" method "+" method return value "+" called "+ Target +": "+returnvalue); }}

Configure Applicationcontext.xml

<!--declaring the entity class to be created -    <BeanID= "Daoimpl"class= "Cn.cnsdhzzl.dao.impl.UserEntityDaoImpl"></Bean>    <BeanID= "Biz"class= "Cn.cnsdhzzl.biz.impl.UserEntityBizImpl">        < Propertyname= "DAO"ref= "Daoimpl"></ Property>    </Bean>    <BeanID= "Loggerbefore"class= "Cn.cnsdhzzl.aop.LoggerBefore"></Bean>    <BeanID= "Loggerafterreturning"class= "Cn.cnsdhzzl.aop.LoggerAfterReturning"></Bean>    <!--Defining Pointcuts -    <Aop:config>        <Aop:pointcutID= "Pointcut"expression= "Execution (public void Save (cn.cnsdhzzl.entity.UserEntity))" />        <!--Insert Enhancement processing (weave in) -        <Aop:advisorAdvice-ref= "Loggerbefore"Pointcut-ref= "Pointcut" />        <Aop:advisorAdvice-ref= "Loggerafterreturning"Pointcut-ref= "Pointcut" />    </Aop:config>

Note:

Exection is a pointcut indicator in which a pointcut expression is used to configure the method to be cut in, and the pointcut expression supports fuzzy matching

 

  • Execution of any public method:
    Execution (Public * * (.. ))
  • The execution of a method whose name begins with "set":
    Execution (* set* (.. ))
  • AccountServiceExecution of any method defined by the interface:
    Execution (* com.xyz.service.accountservice.* (.. ))
  • Execution of any method defined in the service package:
    Execution (* com.xyz.service.*.* (.. ))
  • Execution of any method defined in a service package or its child packages:
    Execution (* com.xyz.service). *.*(.. ))
  • Any connection point in the service package (only method execution in spring AOP):
    Within (com.xyz.service.*)
  • Any connection point in the service package or its child package (only method execution in spring AOP):
    Within (Com.xyz.service. *)
  • AccountServiceany connection point that implements the proxy object for the interface (only method execution in spring AOP):
    This (Com.xyz.service.AccountService)
    ' This ' is more commonly used in binding forms:-See the following notification section for information on how to make a proxy object available in the notification body.  
  • AccountServiceany connection point that implements the target object of the interface (only method execution in spring AOP):
    Target (Com.xyz.service.AccountService)
    ' target ' is more commonly used in binding forms:-See the following notification section for information on how to make a target object available in the notification body.  
  • Either one takes only one parameter, and the arguments passed in at run time are the Serializable connection points of the interface (only method execution in spring AOP)
    Args (java.io.Serializable)
    ' args ' is more commonly used in binding forms:-See the following notification section for information on how to make method parameters available in the notification body. Note that the pointcut given in the example differs from the execution(* *(java.io.Serializable)) following: The args version only matches when the incoming parameter is serializable at dynamic runtime, whereas the execution version declares only one type of parameter in the method signature Serializable .
  • Any connection point in the target object that has an @Transactional annotation (only method execution in spring AOP)
    @target (org.springframework.transaction.annotation.Transactional)
    ' @target ' is more commonly used in binding forms:-See the following notification section for information on how to make a callout object available in the notification body.  
  • The type of any target object declaration has a @Transactional connection point for annotations (only method execution in spring AOP):
    @within (org.springframework.transaction.annotation.Transactional)
    ' @within ' is more commonly used in binding forms:-See the following notification section for information on how to make a callout object available in the notification body.  
  • Any one executed method has an @Transactional annotated connection point (only method execution in spring AOP)
    @annotation (org.springframework.transaction.annotation.Transactional)
    ' @annotation ' is more commonly used in binding forms:-See the following notification section for information on how to make a callout object available in the notification body.  
  • Any one that accepts only one parameter, and the parameter type passed in by the runtime has an @Classified annotated connection point (only method execution in spring AOP)
    @args (com.xyz.security.Classified)
    ' @args ' is more commonly used in binding forms:-See the following notification section for information on how to make a callout object available in the notification body.  
  • Any tradeService connection point above the spring bean named ' ' (only method execution in spring AOP):
    Bean (TradeService)
  • Any connection point above the spring bean whose name matches the wildcard expression " *Service (only method execution in spring AOP):
    Bean (*service)

Spring's first knowledge of IOC&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.