Spring study notes - Getting Started

What is Spring

First Spring is a lightweight Inversion of Control (IoC) and section (AOP) facing the container frame

Spring framework is due to the complexity of software development created. Spring is the basic JavaBean used to do things previously only be done by EJB. However, Spring is not limited to the use of server-side development. The vast majority of Java applications can benefit from the simplicity, testability and loose coupling from the perspective of Spring.

In other words, we learn that Spring is to learn the concept of ideology is IoC and AOP. Its scope is broad, so that any application can benefit from.

Spring advantage

  • Less intrusive / low coupling (reduce the coupling between the components, software decoupling between the layers)
  • Declarative transaction management (based on section and practices)
  • To facilitate integration with other frameworks (e.g. MyBatis, Hibernate)
  • Java developers reduce the difficulty
  • Spring Framework J2EE platform comprises a layer of each solution (stop)

Spring framework

Spring

Some concepts

  • pojo namely Plain Old Java Objects, plain old Java objects
  • JavaBean that meet the Java class JavaBean specification. Written in JAVA JavaBean is a reusable component. It is written in the JavaBean, and specific class must be public, and with no argument constructor. JavaBean by providing a common method in line with the consistency of design patterns will expose internal domain member properties, set and get methods to obtain. As we all know, the attribute name in line with this model, and other Java classes can be found through the operation of these attributes JavaBean introspection mechanism (reflection).

IoC

IoC: Inverse of Control (inversion control)

  • Read as "inversion of control", a better understanding, not a technical, but a design idea is to create objects originally in the program manual control, handed over to the Spring framework to manage.
  • Positive control: To use an object, you need to create your own objects to be responsible
  • Anti-control: To use an object, just get the container from the object you want to use Spring, do not care about the object creation process, which is the reverse of control to create an object of the Spring Framework
  • Hollywood rule: Do not call me, I'll call you

A common example of
traditional methods:
The traditional way of building objects
the traditional model, we have this code implementation

Juice juice = new Juice("橙子","多糖","超大杯");

Factory pattern:
Factory Pattern
Again, we have achieved the following code:

Shop shop = new Shop("橙子","多糖","超大杯");
Juice juice = Shop.makeJuice();

In fact, for such a simple class, we need to introduce the factory model to increase in complexity, but for more complex classes (if oranges, sugar is a relatively complex class), then we use the factory will reduce the administrative costs of the code.

Remember this first example, we write a simple Spring program.

First, write a pojo (traditional objects)

package pojo;

public class Source {  
    private String fruit;   // 类型
    private String sugar;   // 糖分描述
    private String size;    // 大小杯    
    /* setter and getter */
}

Write assembly bean configuration files

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="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">
 <bean name="source" class="pojo.Source">
 	<property name="fruit" value="橙子"/> 
  	<property name="sugar" value="多糖"/>
  	<property name="size" value="超大杯"/>
 </bean>
</beans>

Then to try Spring

ApplicationContext context = new ClassPathXmlApplicationContext(
        new String[]{"applicationContext.xml"}
);

Source source = (Source) context.getBean("source");
System.out.println(source.getFruit());
System.out.println(source.getSugar());
System.out.println(source.getSize());

Output is as follows:
Export
(our project file structure below)
Here Insert Picture Description
(How to create a Spring project?)
We use the IDEA
Here Insert Picture Description
Here Insert Picture Description
so you get a project that contains a Spring environment.

AOP

If the core Spring IoC, then one of Aspect Oriented Programming with Spring is the most important function in the database transaction program is widely used in section

AOP namely Aspect Oriented Program Oriented Programming
First, Aspect Oriented Programming thoughts inside, the functions are divided into core business functions, and peripheral functions.

  • The so-called core business, such as landing, increase data, delete data call core business
  • The so-called peripheral functions, such as performance statistics, logs, transaction management, etc.
    peripheral functions in the programming section of Spring AOP thought for years, it has been defined as section

In Aspect Oriented Programming AOP thoughts inside, cut core business functions and function independently develop, then cut features and core business functions "weaving" together, which is called AOP

Among AOP concepts:

  • Entry point (Pointcut) on which the class, which means cut (WHERE)
  • Notification (Advice) what actually method performed (when: the former method / methods / method before and after) what (what: Enhanced functions)
  • Section (Aspect) section = + entry point for notifications, popular point is: At what time to what, do what enhancements!
  • Weaving (Weaving) The section was added to the object and create a proxy object of the process. (Completed by Spring)

AOP programming

We adopt profile way to carry out a demonstration

First, we prepared a core function:

package service;

public class ProductService {
    public void doSomeService(){
        System.out.println("doSomeService");
    }
}

There are peripheral functions

package aspect;
//这里的依赖包需要额外安装,建议看这个教程:https://blog.csdn.net/shuduti/article/details/53069241
import org.aspectj.lang.ProceedingJoinPoint;

public class LoggerAspect {
    
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("start log:" + joinPoint.getSignature().getName());
        Object object = joinPoint.proceed();
        System.out.println("end log:" + joinPoint.getSignature().getName());
        return object;
    }
}

Configured in accordance with document editing IoC way

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean name="productService" class="service.ProductService" />
    <bean id="loggerAspect" class="aspect.LoggerAspect"/>
</beans>

Writing Test Methods

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[]{"applicationContext.xml"}
    );
    ProductService productService = (ProductService) context.getBean("productService");
    productService.doSomeService();
}

Run
Here Insert Picture Description
Next, is the focus of this section

We used to cut into AOP

We want to doSomeService () as the starting point , in their before and after the implementation of enhanced logging

Such configuration

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean name="productService" class="service.ProductService" />
    <bean id="loggerAspect" class="aspect.LoggerAspect"/>

    <!-- 配置AOP -->
    <aop:config>
        <!-- where:在哪些地方(包.类.方法)做增加 -->
        <aop:pointcut id="loggerCutpoint"
                      expression="execution(* service.ProductService.*(..)) "/>

        <!-- what:做什么增强 -->
        <aop:aspect id="logAspect" ref="loggerAspect">
            <!-- when:在什么时机(方法前/后/前后) -->
            <aop:around pointcut-ref="loggerCutpoint" method="log"/>
        </aop:aspect>
    </aop:config>
</beans>

Run:
Here Insert Picture Description
We obtained the log function, but does not modify the business code

Published 14 original articles · won praise 0 · Views 760

Guess you like

Origin blog.csdn.net/weixin_43819675/article/details/103958271