IoC and AOP of Spring Framework

Posted by Bea on Sat, 18 May 2019 11:28:45 +0200

Introduction to Spring Framework:

In February 2003, the Spring Framework became an open source project and was released in SourceForge. Solutions devoted to Java EE applications, rather than focusing only on one level of solutions, are the "one-stop" choice for enterprise application development. Throughout the presentation layer, business layer and persistence layer, it does not replace the existing framework, but with a high degree of openness and seamless integration of them.

Note: First, download the required version of spring resources through the address of Spring official website http://repo.spring.io/replease/org/spring framework/spring/.

Spring IoC:

Ioc: Control inversion, also known as dependency injection, is an object-oriented design concept used to reduce the coupling between program codes.
Control Inversion (Dependency Injection): Containers (such as Spring) are responsible for injecting (assigning) specific objects on which components depend to avoid hard-coded coupling.

Using Ioc injection:

Import the required jar package and create the spring core 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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    ">

</beans>

1. Setting value injection:

1     <bean id = "helloSpring" class="cn.demo.HelloSpring">
2         <property name="str" value="Spring"></property>
3     </bean>

id: Give it a unique name to access. If you want to specify more aliases, you can use the name attribute, separated by commas, semicolons, and spaces.

Class: The fully qualified name of the class to be injected.

property:

Name: The method name of the setter for the property, so the setter method must be provided for setting injection.

Value: The value assigned to an attribute.

2. Constructional injection: using constructional methods to assign values.

1     <bean id="user" class="cn.bdqn.pojo.User">
2         <constructor-arg index="0" name="id" value="1"  type="integer"></constructor-arg>
3         <constructor-arg index="1" name="name" value="Spring"></constructor-arg>
4     </bean>
constructor-arg: A parameter that represents the constructor's method and is used in an indistinguishable order.
index: Subscription of parameters. (subscripts start at 0)
Name: The name of the parameter.
Value: The value assigned to the parameter.
type: type of parameter.
When used, it is not necessary to specify all the above attributes. Select attributes for injection according to requirements.

3. Implementing attribute injection using p namespace:

<bean id="userDao" class="cn.dao.imp.UserDaoImp"></bean>    
<bean id="user" class="cn.pojo.User" p:id="1" p:name="Spring"  p:dao-ref="userDao"></bean>

p: Attribute name = "Attribute value"

p: Attribute name - ref = Bean id

The use of p namespace for injection is also achieved through the setter method of attributes. The setter method for this attribute must be provided.

Test Injection Results: (Writing Test Classes)

 1 package cn.test;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 import cn.bdqn.pojo.User;
 6 import cn.bdqn.service.IUserService;
 7 import cn.bdqn.service.imp.UserServiceImp;
 8 
 9 
10 public class test {
11     public static void main(String[] args) {
12         ApplicationContext c = new ClassPathXmlApplicationContext("app.xml");//Read Spring Core Profile
13     User user = (User) c.getBean("user");//Getting instance objects of this class through the id of the bean
14         //Output class injected attribute values. Example: user.getName(); // Reads the value of name in the user class.
15 } 16 }

In Spring, bean s can be defined as two patterns: prototype (multiple cases) and singleton (singleton)

Singleton (singleton): Only one shared instance exists, and all requests for this bean return this unique instance.

prototype (multiple examples): Each request to this bean creates a new bean instance, similar to new.

Spring bean s default to singleton mode. You can modify it to multiple-case mode by scope="prototype".

<bean id="user" class="cn.pojo.User" scope="prototype">

 

Inject different data types:

1. Injection of direct quantities (basic data types, strings):

For basic data types, and their wrapper classes, strings, in addition to the value attribute, can also be injected through < value > sub-elements.

1 <property name = "name">
2         <value>Zhang San</value>
3 </property>

If the attribute value contains special characters in XML (&, <, >, "'), it needs to be processed when injecting:

1. Use <[! CDATA []> Tags

1 <property name = "name">
2      <value><![CDATA[P&G]]></value>
3  </property>

2. Replace special characters with entity references.

1 <property name = "name">
2      <value>P&amp;G</value>
3  </property>

XML predefined entity references:

  < : &It;     > : &gt;   &: &amp;  ': &apos;  " : &quot;

Note: Only < and & are illegal in XML, and the other three are legal, but it's a good habit to replace entity references.

2. Refer to other Bean components:

Bean s defined in Spring can refer to each other to establish dependencies. In addition to using ref attributes, they can also be implemented through < ref > sub-elements.

<property name = "dao">
        <! -- The dao attribute assignment for userService refers to an object whose id is userDao - > The
        <ref bean = "userDao">
</property>
<property name = "dao">
        <! -- The dao attribute assignment for userService refers to an object whose id is userDao - > The
        <ref local= "userDao">
</property>

Local attributes and bean attributes are used almost identically to specify the id of the bean to be referenced. The difference is that Spring configuration files can be split into multiple files. The local attribute can only retrieve the id in the same configuration file, while the bean attribute can retrieve the id of the bean in other configuration files.

3. Use internal beans:

If a Bean group needs to be used only in one place, it can be defined as an internal Bean.

<! - Assigning the dao attribute of userService calls the serDao method - >.
<property name = "dao">
 <! -- Define the userDao object (this userDaoImp can only be used by this userService and can't be called by other beans) -->
 <bean class="dao.imp.UserDaoImp"/>
</property>

4. Attributes of injection set type:

1. Note List or array type attributes can be injected using the < list > tag.

<property name = "list">
    <list>
        <! -- Defines elements in list s or arrays - >
            < value > Set 1 </value >
            < value > Set 2 </value >
    </list>        
</property>

Note: List tags can be used to inject collection elements, or even a list tag, using tags such as value, ref, etc.   

2. For set, set tags can be used for injection.

<property name = "set">
    <set>
        <!-- Definition set Elements in -->
            <value>Set 1</value>
            <value>Set 2</value>
    </set>        
</property>

Note: set tags can be used to inject collection elements with tags such as value, ref, etc.

3. For Map type attributes.

 1 <property name = "map">
 2     <map>
 3         <!-- Definition map Key-value pairs in -->
 4             <entry>
 5                 <key><value>map Key 1</value></key>
 6                 <value>map The value is 1</value>
 7             </entry>
 8 
 9             <entry>
10                 <key><value>map Key 2</value></key>
11                 <value>map The value is 2</value>
12             </entry>
13     </map>        
14 </property>

Note: If the key or value in the map is a Bean object, you can replace the value in the above code with ref.

4. For properties of type Properties.

<property name = "prop">
    <props>
        <!-- Definition Properties Elements in -->
            <prop key = "Key 1">Value 1</prop>
            <prop key = "Key 2">Value 2</prop>
    </props>        
</property>

Note: The keys and values in Properties are usually string types.

5. Injecting null and empty string values

<!-- Inject null string values -->
<property name = "id"><value></value></property>

<!-- injection null value -->
<property name = "name"><null/></property>

-----------------------------------------------------------------------------------------------------------------------------------------------

Spring AOP:

Face-Oriented Programming: It is the product of the development of software programming thought to a certain stage. It is a useful complement to object-oriented. Usually used in situations with crosscutting logic, such as scope control, transaction management, performance detection, etc. Face-oriented simply means adding some new functions to the code segment without changing the source program, and enhancing the code segment. The design idea comes from the agent design pattern.

Aspect: A modular cross-cutting logic (or cross-cutting concerns) may cross-cut multiple objects.

Join Point: Find the location of the tangent point through the join point.

Advice: Common functions scattered across the system. Log management transaction management.

Pointcut: The location where enhanced code needs to be placed.

Target object: An object enhanced by one or more facets.

AOP proxy: Objects created by the AOP framework to implement enhanced processing functions.

Weaving: The process of connecting enhanced processing code to a type or object in an application.

Enhancement type processing: pre-enhancement, post-enhancement, surround enhancement, exception throw enhancement, and final enhancement.

Note: Aspects can be understood as consisting of enhancement processing and entry points, which include both the definition of crosscutting logic and the definition of join points. Aspect-oriented programming mainly concerns two issues, one is where it is located, and the other is what functions it performs. Spring AOP is the framework responsible for implementing aspects. That is to say, weaving is done by AOP.

1. Enhancement with AOP:

1. Define Enhancement Classes:

 1 package cn.bdqn.advice;
 2 
 3 import org.apache.log4j.Logger;
 4 import org.aspectj.lang.JoinPoint;
 5 import org.aspectj.lang.ProceedingJoinPoint;
 6 
 7 public class ServiceLoggingAdvice {
 8     private Logger logger = Logger.getLogger(ServiceLoggingAdvice.class);
 9     
10     //Preamplifier
11     public void before(JoinPoint joinPoint){
12         String methodName = joinPoint.getSignature().getName();//Get the enhanced method name
13         String className = joinPoint.getTarget().getClass().getSimpleName();//Get the enhanced class name
14         logger.debug("Pre-enhancement...");
15     }
16     
17     
18     //Post enhancement
19     public void after(JoinPoint joinPoint){
20         String methodName = joinPoint.getSignature().getName();//Get the enhanced method name
21         String className = joinPoint.getTarget().getClass().getSimpleName();//Get the enhanced class name
22         logger.debug("Post-enhancement...");
23     }
24     
25     //Abnormal enhancement
26     public void thowing(Exception e){
27         logger.debug(e.getMessage());
28     }
29     
30     //Final enhancement
31     public void afterEnd(JoinPoint joinPoint){
32         String methodName = joinPoint.getSignature().getName();//Get the enhanced method name
33         String className = joinPoint.getTarget().getClass().getSimpleName();//Get the enhanced class name
34         logger.debug("Final enhancement");
35     }
36 
37     //Surround enhancement
38     public Object round(ProceedingJoinPoint joinPoint){
39         Object result = null;
40         try {
41             logger.debug("Surround enhancement----Preposition");
42             result = joinPoint.proceed();
43             logger.debug("Surround enhancement---Postposition");
44         } catch (Throwable e) {
45             e.printStackTrace();
46         }
47         return result;
48     }
49 }

 

Note: JoinPoint join points can be used to obtain information about the target method, such as the class, method name, method access modifier and so on.

Around the enhancement method, you declare parameters of ProceedingJoinPoint type, and you can get information about the join point in the same way as JoinPoint. JoinPoint is a sub-interface of JoinPoint. It encapsulates not only the target method and target parameters, but also the proxy target object. Through its proceed() method, the real target method can be invoked to achieve complete control of the connection point.

2.Spring configuration file for AOP-related configuration:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3     xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xmlns:aop="http://www.springframework.org/schema/aop"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 8     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 9     http://www.springframework.org/schema/aop 
10     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
11     ">
12 
13     <!-- AOP -->
14    <!-- Enhancement class --> <bean id="advice" class="cn.bdqn.advice.ServiceLoggingAdvice"></bean>
15     <aop:config>
16         <aop:pointcut expression="execution(* cn.bdqn.service..*.*(..))" id="point"/>
17         <aop:aspect ref="advice">
18         
19 <!--     Preamplifier      <aop:before method="before"  pointcut-ref="point" /> -->
20 <!--     Abnormal throw enhancement   <aop:after-throwing method="afterThrowing" pointcut-ref="point" throwing="e"/> -->
21 <!--     Final enhancement      <aop:after method="afterEnd" pointcut-ref="point"/> -->
22 <!--     Post enhancement      <aop:after-returning method="after" pointcut-ref="point"/> -->
23 <!--     Surround enhancement      <aop:around method="around" pointcut-ref="point"/> -->
24         </aop:aspect>
25     </aop:config>
26 </beans>

1. Pre-enhancement: Pre-enhancement using <aop:before> is performed before the target method.

2. Post-enhancement: Post-enhancement is performed using <aop:after-returning> after the target method. (If an exception occurs to the target method, post-enhancement will not be performed whether try-catch is used or not.)

3. Exception throw enhancement: use < aop: after-throwing > for exception throw enhancement, weave enhancement code when the target method throws an exception.

4. final enhancement: final enhancement with < aop: after >. (If an exception occurs to the target method, the final enhancement will be performed regardless of whether try-catch is used or not.)

5. Enhancement of surround: Enhancement of surround can be woven into the target method before and after using <aop:round>. The most powerful type of enhancement processing, Spring gives all the control of the target method to it. In the surrounding enhancement processing, it can obtain or modify the parameters of the target method, return value, exception handling, and even decide whether the target method is executed.

Note: The expression attribute of the tag <aop:pointcut> that configures the pointcut can configure the expression of the pointcut:

execution is the pointcut indicator. The expressions in parentheses are pointcuts, which can configure the features of the enhanced processing of pointcuts and also support fuzzy queries:

1.public * addNewUser(entity.User): * represents a return value that matches all types.

2.public void *(entity.User): * means that all method names match.

3.public void addNewUser(...): "..." denotes the number and type of all parameters.

4.* com.service. *. * (.)): This expression represents all methods that match all classes under the com.service package.

5.* com.service. *. * (.)): This expression represents all methods that match all classes under the com.service package and its subpackages.

The < aop: aspect > tag refers to beans containing enhancement methods, and then enhances them through various enhancement tags.
Method: Represents a method in an enhancement class.
Point cut-ref: Introducing enhanced entry points.
The throwing attribute in exception enhancement represents the parameter name of the exception.

Topics: Java Spring Attribute xml Programming