Spring IoC and AOP Extensions
IoC: Control Inversion
The life cycle management of objects is handed over to Spring, and the property injection (DI) of objects is also handed over to Spring. (IoC container / Spring container - > bean-oriented programming)
AOP: Face-Oriented Programming
On the basis of not changing the original code, a series of functions are added dynamically in the process of program running by using proxy mechanism (bringing together common functions).
1. Master different dependency injection methods (DI-IoC)
1.1 Master Set Value Injection (Most Important) - Different Data Types
Set value injection, which is the most widely used dependency injection method in Spring, is very consistent with our previous development habits. Dependency injection is implemented based on setter method. (Setter strongly recommends that you don't write on your own, let the tools help you generate! )
<!-- TestEntity bean assembly --> <bean id="testEntity" class="cn.kgc.demo1.TestEntity"> <!-- Special character value 1 --> <property name="specialCharacter1" value="1<2"></property> <!-- Special character 2 --> <property name="specialCharacter2"> <value><![CDATA[2<1]]></value> </property> <!-- external bean Introduce --> <!-- <property name="innerBean" ref="user"></property> --> <!-- inside bean Introduce(Can only be used once without id) --> <property name="innerBean"> <bean class="cn.kgc.demo1.User"> <property name="username" value="Small journey"></property> </bean> </property> <!-- Collection type --> <property name="sportList"> <list> <value>Swimming</value> <value>Play chess</value> </list> </property> <!-- array --> <property name="array"> <array> <value>Play chess</value> <value>Swimming</value> </array> </property> <!-- set aggregate --> <property name="set"> <set> <value>Singing jump</value> <value>RAP</value> </set> </property> <!-- map aggregate --> <property name="map"> <map> <entry> <key> <value>CN</value> </key> <value>The Chinese people</value> </entry> </map> </property> <!-- Properties type --> <property name="props"> <props> <prop key="US">U.S.A</prop> </props> </property> <!-- Empty string --> <property name="emptyValue" value=""></property> <!-- null value --> <!-- <property name="nullValue" value="null"></property> --> <property name="nullValue"> <null/> </property> </bean>
1.2 Master tectonic injection
Implement injection based on construction method (with parameter construction)!
The previous set-value injection used a parameter-free construct (default call).
public class UserService { private String username; private User user; private int age; // Conflict issues of compatible types such as: 12 can be stored as either a string or a value // When compatibility issues arise, it assigns values in the order of construction parameters. public UserService(User user,String username,int age) { this.user = user; this.username = username; this.age = age; } // Constructing Method of Multiple Different Types of Parameters /*public UserService(User user,String username) { this.user = user; this.username = username; }*/ // Single parameter construction method /*public UserService(String username) { this.username = username; }*/ public UserService() { } public void test() { System.out.println("User name:"+username); System.out.println("The user's age is:"+age); System.out.println("User User name:"+user.getUsername()); } }
<bean id="userService" class="cn.kgc.demo2.UserService"> <!-- The following index type name Attribute understanding is enough --> <!-- <constructor-arg value="12" index="2"/> --> <!-- <constructor-arg value="12" type="int"/> --> <constructor-arg value="12" name="age"/> <constructor-arg value="Xiao Ming"/> <constructor-arg ref="user"/> </bean> <!-- <bean id="userService" class="cn.kgc.demo2.UserService"> //Construction Injection: A Method for Constructing Multiple Different Types of Parameters <constructor-arg value="Xiao Ming"/> <constructor-arg ref="user"/> </bean> --> <bean id="user" class="cn.kgc.demo2.User"> <property name="username" value="Xiao Ming"></property> </bean> <!-- <bean id="userService" class="cn.kgc.demo2.UserService"> //Construction Injection: A Single Parameter Construction Method <constructor-arg value="Xiao Ming"/> </bean> -->
1.3 Master p Namespace Injection
p namespace injection is based on set value injection, which is more concise in writing.
xmlns:p="http://www.springframework.org/schema/p"
<bean id="userService" class="cn.kgc.demo3.UserService" p:username="Xiao Ming" p:user-ref="user"/>
2. Master more types of enhancement processing (AOP)
Pre-enhancement
Posterior enhancement
Abnormal throw enhancement
// Exception throw enhancement enhancements performed when an exception occurs public void throwsExceptionMethod(JoinPoint jp,Exception e) { Signature signature = jp.getSignature(); // Get the method name String methodName = signature.getName(); logger.error("<=="+methodName+"Exceptions to method execution<==The exception information is:"+e); }
<aop:after-throwing method="throwsExceptionMethod" throwing="e" pointcut-ref="logPointCut"/>
Final enhancement
// Ultimately enhance final execution content public void afterMethod(JoinPoint jp) { Signature signature = jp.getSignature(); // Get the method name String methodName = signature.getName(); logger.error("<=="+methodName+"Method is executing the final processing content"); }
<aop:after method="afterMethod" pointcut-ref="logPointCut"/>
Enhancement around: All of the above enhancements are integrated
// Enhancement of surround public Object aroundMethod(ProceedingJoinPoint jp) { Signature signature = jp.getSignature(); String methodName = signature.getName(); String argStr = Arrays.toString(jp.getArgs()); // Pre-enhancement logger.info("==>Executing"+methodName+"Method==>The method parameters are as follows:"+argStr); // This return value should correspond to the return value type of the corresponding method. Object returnResult = null; try { // Target implementation approach returnResult = jp.proceed(); // Posterior enhancement logger.info("<=="+methodName+"Method Execution End<==Method return value is:"+returnResult); } catch (Throwable e) { e.printStackTrace(); // Abnormal throw enhancement logger.error("<=="+methodName+"Exceptions to method execution<==The exception information is:"+e); }finally { // Final enhancement logger.error("<=="+methodName+"Method is executing the final processing content"); } return returnResult; }
<aop:around method="aroundMethod" pointcut-ref="logPointCut"/>
3. Master Annotations to Realize IoC and AOP
XML (closer to basic implementation) - > XML + Annotations - > Pure Annotations
3.1 Implementing IoC
The following annotations can help you generate bean s automatically: (IoC)
@ Controller presentation layer
@ Service Business Logic Layer
@ Repository Data Access Layer
@ Component components/components (classes suitable for non-three-tier architectures) are generic
The following annotations enable automatic dependency injection: (DI)
@ Autowire is suitable for object attribute injection. Both Autowire and Resource can be injected by name and type (automatic lookup).
@ Resource is suitable for object attribute injection
@ Value Suitable for Common Value Injection
3.2 Implementing AOP
@Component // <bean id="loggerIncreseClass" class="cn.kgc.demo4.increse.LoggerIncreseClass"/> @Aspect // <aop:aspect ref="loggerIncreseClass"> public class LoggerIncreseClass { private Logger logger = Logger.getLogger(LoggerIncreseClass.class); @Pointcut("execution(* cn.kgc.demo6.UserService.*(..))") public void pointCut() {}; // Enhancement of surround // @Around("execution(* cn.kgc.demo6.UserService.*(..))") @Around("pointCut()") public Object aroundMethod(ProceedingJoinPoint jp) { Signature signature = jp.getSignature(); String methodName = signature.getName(); String argStr = Arrays.toString(jp.getArgs()); // Pre-enhancement logger.info("==>Executing"+methodName+"Method==>The method parameters are as follows:"+argStr); // This return value should correspond to the return value type of the corresponding method. Object returnResult = null; try { // Target implementation approach returnResult = jp.proceed(); // Posterior enhancement logger.info("<=="+methodName+"Method Execution End<==Method return value is:"+returnResult); } catch (Throwable e) { e.printStackTrace(); // Abnormal throw enhancement logger.error("<=="+methodName+"Exceptions to method execution<==The exception information is:"+e); }finally { // Final enhancement logger.error("<=="+methodName+"Method is executing the final processing content"); } return returnResult; } }
<!-- Enable AOP annotation --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy>