Spring Learning Notes - Foundation

Keywords: Spring Attribute xml Java

Introduction to Spring

spring is an open source lightweight Java EE framework. It uses a layered architecture. The main part is the implementation of AOP and IOC container code. Enhance reusability and loose coupling, with dynamic scalability

Project Construction of Eclipse and IDEA

Eclipse is generally much better configured than Idea

Eclipse

  • Create a new Project, you can
  • Import external Jar packages to form new Libraries
  • If you are a Java Web project, you also need to copy all Jar packages into the web/WEB-INF/lib directory
  • Create the application Context. XML file in the src directory

Idea

  • Create a Java project, select Spring 4 from the right sidebar, and tick the number
  • Select Use Libraries below, and then select the required Jar package to import into Libraries
  • Free Settings Along the Way
  • Create the application Context. XML file in the src directory after entering the project
  • To configure the appropriate Artifact, Facets and Modeles for the project is to select the file configuration path or something. If there is something wrong or missing, there will be a hint at the bottom right. Click fixed and it will automatically adjust.

Assembly of configuration files

In general, the xml file content is configured so that it is generic

<?xmlversion="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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.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
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.1.xsd">
     
<beans>

IOC/DI

IOC: Control inversion, sometimes called DI, or dependency injection. It can be understood as follows:

IOC containers are designed to manage beans and create a memory area in which code that operates beans can be developed in an Interface-oriented manner.
In this way, based on the polymorphism of the interface, the hierarchy of the program structure is more flexible, and the maintenance and expansion are also convenient. The IOC concept technically separates interfaces from implementations.

IOC container

JavaBeans can be fully managed through IOC containers, including creation, destruction, automated transaction processing of JavaBeans in databases, and support some enterprise-level applications. Spring's IOC container is completely separated from the platform. It uses the simplest JavaBean technology to realize the separation of interface and implementation, and provides good support for component deployment.

Start with the following:

Prepare a JavaBean first

public class CategoryBean {
    private int id; 
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Be careful

Experiments show that if the getter and setter methods of variables are not standardized, errors will occur when the program runs. So it's recommended to follow.
set+Variale_name and get+Variable_name to name getter and setter methods

Add Bean Configuration to the applicationContext.xml File

<beans ....>
    <bean name="cate" class="pojo.Category">
        <property name="name" value="hellosocra" />
    </bean>
</beans>

Here we need to explain the configuration details:
- First is the name attribute in the tag, where you create a CategoryBean object called cate
- The id and name attributes of tags in xml configuration files are basically the same, but using id will be more standard because the id requirement is unique in xml
- The value of the class attribute is the path of CategoryBean.java, with the package name added.
- Labels are used to assign attributes in object cate. The getter and setter methods of variables are automatically invoked to assign values. If the names are not standardized, they cannot be assigned.
- name corresponds to the attribute name of cate, value is assignment, and this example assigns the value of the name attribute to hellosocra
- You can also use ref to link attribute values, and then use the value at the link, which is also the process of injecting values.

Objects that use injection

Now that the configuration of the injected object has been added, let's see how to use the injected object.

public class TestSpring {

    public static void main(String[] args) {
        // 1. Necessary statements can be defined as global variables 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });

        // 2. Start using IOC's getBean() method to get objects, but mainly force type conversion
        Category cate = (Category) context.getBean("cate");
        // 3. The Method of Using Bean Objects
        System.out.println(cate.getName());
    }
}

Annotation Configuration IOC

Just as annotation configurations are used when learning Servlet s, annotation configurations can also be used here. There are two kinds of annotation configurations

Annotations for "Injection Object Behavior"

The following approach is focused on injection when one JavaBean is an attribute of another JavaBean
- Configuration of injecting attributes of an object before annotation (configuration objects are injected and assigning attributes to objects are injected as well)
- Add <context: annotation-config/> to indicate that spring is configured with annotations
- Add the @Autowired annotation before the corresponding attribute of the object is injected, or the @Autowired annotation before the setter method of the corresponding attribute
- Add the @Resource (xxx = xxxx) annotation before injecting attributes in the object (another JavaBean acts as attributes of the bean), for example

class ABean{
  String name ;
  int id;
  // .... getter and setter methods
}

class BBean{
  @Resource(name="socra",id=5)
  A a; // A as the attribute of B
  int no;
  // .... getter and setter methods
}

Notes for "Bean"

Likewise, the following approach is focused on injection when one JavaBean is an attribute of another JavaBean
- Annotate all tags in the tag in the xml file
- Add <context: componment-scan base-backage= "package and Bean name of JavaBean"> to indicate that all beans required for spring are in this path
- Then add @Compent("name") before all bean class definitions under the package. The table name is Bean, and the name is the object name of the bean class to be injected.
- If one class is an attribute of another class, add the @Autowire annotation before the attribute
- The rest of the attributes can be freely assigned

IOC Principle

The traditional way to create objects: create an object by using the new keyword
IOC: The declaration cycle of an object is managed by Spring, and a pair of objects is obtained directly from Spring. IOC is inversion control, meaning that the control of the original object is in the hands of the user and is now handed over to Spring in turn.

To make an analogy:
Traditionally, it is equivalent to going to the vegetable market for new chickens, but raw chickens need to pluck their hair, remove their internal organs, and then pepper, soy sauce, baking, after a variety of processes, before they can be eaten.
IOC: It's equivalent to going to a Spring and ordering a chicken all the time. When you hand it in, it's full of flavors. You just eat it.

Interpretation is vivid and vivid, (funny)

AOP

AOP: Aspect-oriented programming, which means programming for a small piece of code. AOP divides function into core function and peripheral function, and peripheral function is defined as tangential Aspect in Spring's AOP thought. This selective, low-coupling programming idea, which combines tangent and core business functions, is called tangent programming.
The so-called AOP idea is that two functions are developed independently and then "woven" together.

AOP can do some functional enhancements without changing the original code

Additional Jar packages are required: aspect.jar and aopliance.jar

Preparing a Core Business Bean and Face Aided Bean

/**
 * Bean as a Core Business
 */
public class ProductService{
    public void dosomeService(){
        System.out.println("dosomeService");
    }   
}
/**
 * Bean as sectional AIDS
 */
public class LoggerAspect {
    public Object log(ProceedingJoinPoint joinPoint){
        Object obj = null;
        System.out.println("start log: " + joinPoint.getSignature().getName());
        try {
            obj = joinPoint.proceed();// Continue executing, this example means executing dosomeService()
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("end log: " + joinPoint.getSignature().getName());
        return obj;
    }

}

Add Configuration

<beans ....>
    <!-- 1.Declare core business objects -->
    <bean id="s" class="service.ProductService"></bean>
    <!-- 2.Statement Auxiliary Log Aspects -->
    <bean id="loggerAspect" class="aspect.LoggerAspect"></bean>
    <!-- 5.adopt aop:config Work out business objects and ancillary functions together -->
    <aop:config>
        <!-- 3.Specify core business functions -->
        <aop:pointcut id="loggerCutpoint"
            expression=
            "execution(* service.ProductService.*(..))"/>
        <!-- 4.Designated Auxiliary Functions -->
        <aop:aspect id="logAspect" ref="loggerAspect">
            <aop:around pointcut-ref="loggerCutpoint" method="log"/>
        </aop:aspect>
    </aop:config>
</beans>
  • First of all, we need to specify core business beans and aspect-assisted beans, and set their object names and paths.
  • The label has a well-specified core business and a section assistant entry, and the id attribute is the object name.
  • The general value of the expression attribute in the core business bean is execution(* package_name.Bean_name. *(.)), which represents the method entry in the core business bean (there can be more than one method in the core business).
  • The id is injected into the tag, and the pointcut-ref attribute specifies the object to be assisted by the auxiliary section. Method is the assistant method to call the auxiliary section.

So far, tangential assistance has been set up. From top to bottom, the core business functions are implemented first and then the auxiliary business is implemented.

Use

Because using AOP, the steps of using AOP are the same as without adding section, because this also reflects the superiority of AOP.

public class TestAspect {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext apc = new 
                ClassPathXmlApplicationContext("applicationContext.xml");

        ProductService s = (ProductService)apc.getBean("s");
        s.dosomeService();
    }

}

Advanced usage of AOP

I wanted to write it directly this time, but next time I'll write it together with the advanced usage of IOC. It's a lazy dig.
Oh, of course, AOP's annotation is 23333 next time.

have not seen for a long time

After a long time of Java EE learning, we are finally on the agenda. We are ready to fill the pit with Servlet s and Jsp s that we left out before.

Now dig a hole: Servlet learning summary notes, Jsp summary notes, Spring more advanced usage etc.

PS: First of all, summarize the configuration methods of these frameworks. idea is really troublesome to configure. .F__k

Posted by Stole on Tue, 02 Jul 2019 13:57:33 -0700