spring Basic Knowledge - --- Introduction to spring, IOC Derivation, hellospring, Modification of Test demo, IOC Creation Objects, spring Configuration File

1. Introduction to spring

Brief Introduction to spring

Single Hell: servlet, jdbc, jsp...
Framework to replace JDBC: MyBatis;
In 2002, Rod johnson first introduced Spring Framework's predecessor, interface21 Framework
In 2003, Spring Framework was redesigned based on interface21 Framework and released 1.0 official version.
Spring official website: https://spring.io/
Spring Download: https://spring.io/projects/spring-framework#learn
Version Description:
We will encounter releases, stable, alpha, beta, pre, current, eval, rc, snapshot and other versions when downloading software, especially when downloading plug-ins. Now I will explain what the following version means.

1, snapshot (snapshot), or development version, when we create maven project, the editor will automatically fill in 1.0-SNAPSHOT version, or 1.0 development version, which can not be used, because the version is in the process of development, so the runtime will be updated from time to time, resulting in functional changes, and can not be used in the formal environment. Snapshot version library;

2, alpha, internal beta version, from alpha, is an earlier version, mainly for developers and testers to test and find BUG, not recommended to use;

3, beta, public beta, from the alphabet beta, which is a further version than alpha, for public testing, but is not recommended.

4, pre, which is similar to alpha version and sometimes subdivided into M1 and M2 versions, is not recommended.

5. Release Candidate, as its name implies, is a candidate version for software. On the system platform, candidate versions are issued.

6. The release version of GA(General Availability) is officially released, which is explained by GA in foreign countries.

7, release, release, which is the Chinese meaning of release, that is, the official recommended version;

8, stable, stable version, this version is more stable than the beta version, eliminating many bug s in the beta version, improving some functions, it is recommended to use;

9, current, the latest version, but not necessarily stable version, need to see if there are release s or stables and other versions;

10, eval, evaluation version. It may have a month or a fixed time limit.

Spring Advantages

  • Spring is open source and free.
  • Spring is a lightweight, non-intrusive framework.
    • There is no other dependency, use it, and no need to import other packages.
  • IOC AOP
    • IoC
    • AoP
  • Transaction support
  • Support for frameworks can be introduced to other frameworks at no cost. MyBatis, Hibernate, Strut1/2, Spring MVC
    • SSH,SSM

To sum up: Spring is a lightweight control inversion [IOC] and Aspect-Oriented [AOP] framework.

OOP: Object-Oriented Programming

Spring wants to be an adhesive. Developed a set of their own ecology;

Spring Composition

Architecture: MVC three-tier architecture

The Spring framework is a layered architecture consisting of seven well-defined modules. The Spring module is built on top of the core container, which defines how bean s are created, configured, and managed.
Each module (or component) that makes up the Spring framework can exist independently or be implemented in conjunction with one or more other modules. The functions of each module are as follows:

  • Core container: Core container provides the basic functions of Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the Inversion of Control (IOC) pattern to separate application configuration and dependency specifications from the actual application code.
  • Spring context: The Spring context is a configuration file that provides context information to the Spring framework. Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, validation and scheduling functions.
  • Spring AOP: Through configuration management features, the Spring AOP module directly integrates aspect-oriented programming functions into the Spring framework. Therefore, it is easy to enable any object managed by the Spring framework to support AOP. Spring AOP module provides transaction management services for objects in Spring-based applications. By using Spring AOP, declarative transaction management can be integrated into applications without relying on EJB components.
  • Spring DAO: The JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the number of exception codes that need to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exceptions follow the general DAO exception hierarchy.
  • Spring ORM: The Spring framework inserts several ORM frameworks to provide ORM object relational tools, including JDO, Hibernate and iBatis SQL Map. All of this follows Spring's generic transaction and DAO exception hierarchy.
  • Spring Web module: The Web context module is built on the application context module, which provides the context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies processing multiple requests and binding request parameters to domain objects.
  • Spring MVC Framework: The MVC Framework is a full-featured MVC implementation for building Web applications. Through the policy interface, the MVC framework becomes highly configurable and contains a large number of view technologies, including JSP, Velocity, Tiles, iText and POI.

The Spring framework's functionality can be used in any J2EE server, and most of the functionality can also be applied in an unmanaged environment. The core point of Spring is to support reusable business and data access objects that are not bound to specific J2EE services. There is no doubt that such objects can be reused between different J2EE environments (Web or EJB), stand-alone applications, and test environments.

Spring's components:

Spring Boot and Spring Cloud

Spring Boot: A scaffold that can quickly build Spring applications; conventions are greater than configurations, linking the preceding and the following.

Spring Cloud: It's based on Spring Boot; it's an ecosystem;

2.IOC Derivation

Aim: To solve the complexity of enterprise application development

Functions: Replace EJB with basic JavaBean s and provide more enterprise application functionality

Scope: Any Java application

Spring is a lightweight control inversion (IoC) and Aspect-Oriented (AOP) container framework.

Analysis and Implementation

Let's write a code test in the original way: dao - service - front end

Think: Now the front-end transfer or call will not change, all operations are implemented by our program apes;

Solution: Front-end operation, background unchanged; leaving a call interface

The prototype of IOC.

The Essence of IOC

inversion of Control: IOC

He is a design idea. According to this idea, there is a way to implement DI: Dependency Injection.

The essence is to set interfaces. Set method is an abstract thinking.

Inversion: From passive to active, from active control to passive acceptance, by writing code, writing interfaces, the program has a high degree of configurability and dynamic;
The coupling of the program is greatly reduced. Convenience Module Independence: --> Micro Services. Decoupling.

3.HelloSpring

1. Importing jar packages

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.9.RELEASE</version>
</dependency>

2. Create entity classes

package com.kuang.pojo;

public class Hello {

    private String name;

    public Hello() {
    }

    public Hello(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void show(){
        System.out.println("Hello,"+name);
    }

    @Override
    public String toString() {
        return "Hello{" +
                "name='" + name + '\'' +
                '}';
    }
}

3. Write configuration files for spring

<?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 Just one. java Object, by Spring Management and creation-->
    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>

    <!--bean Just one. java Object, by Spring Management and creation-->
    <bean id="hello2" class="com.kuang.pojo.Hello">
        <property name="name" value="WestOS"/>
    </bean>

    <!--// Hello hello2 = new Hello();-->
    <!--// hello2.setName (WestOS)-->

</beans>

4. Test class

package com.kuang.pojo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloTest {
    @Test
    public void test(){

        //Parse the beans.xml configuration file and manage the corresponding Bean objects in production.
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //Get the entity of the object through the Bean
        Hello hello = (Hello)context.getBean("hello2");

        hello.show();

    }
}

Think about it?

  • Who created the Hello object?
    • hello objects are created by Spring.
    • Beans. XML - > Manage bean s, Java objects, Spring is like a container, storing many objects;
      • Parsing configuration files
      • Create objects by reflection and set values
  • How do properties of Hello objects set values?
    • The properties of the hello object are created by the Spring container.
    • This process is called control inversion: IOC

Control: Who controls the creation of objects? Originally: program ape controls, after using Spring, Spring creates objects.

Inversion: The program itself does not create objects and becomes passive acceptance objects.

Dependency Injection: DI is essentially set-based injection.

IOC is a programming idea. From active programming to passive acceptance;

4. Modify the test class Demo

Small Demo that uses Oracle and Mysql to get user information before spring is completed;

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--suppress SpringFacetInspection -->
<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 id="UserDaoImpl" class="com.kuang.dao.UserDaoImpl"/>
    <bean id="UserDaoMysqlImpl" class="com.kuang.dao.UserDaoMysqlImpl"/>
    <bean id="UserDaoOracleDao" class="com.kuang.dao.UserDaoOracleDao"/>

    <bean id="ServiceImpl" class="com.kuang.service.UserServiceImpl">
        <!--Common value usage value,Reference to others bean Use ref-->
        <property name="userDao" ref="UserDaoMysqlImpl"/>
    </bean>

</beans>

Test class

package com.kuang.test;

import com.kuang.service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    @Test
    public void test(){

        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        UserServiceImpl userService = (UserServiceImpl) context.getBean("ServiceImpl");

        userService.getUser();

    }

}

OK, now, we completely do not need to change the program, to achieve different operations, only need to modify in the xml configuration file, the so-called IoC, a sentence: objects created by Spring, management, assembly!

5. How IOC creates objects

How do we usually create objects?

Parametric and non-parametric structures

Let's see how to deal with these two situations in Spring.

Create entity classes

package com.kuang.pojo;

public class User {

    private String name;
    private String sex;
    private int age;

    public User() {
        System.out.println("User Parametric structure");
    }

    public User(String name) {
        System.out.println("User Parametric structure");
        this.name = name;
    }

    public User(String name, int age) {
        System.out.println("User PARAMETRIC STRUCTURES 2");
        this.name = name;
        this.age = age;
    }

    public User(String name, String sex, int age) {
        System.out.println("User Parametric structure 3");
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public void setName(String name) {
        System.out.println(name+":"+System.currentTimeMillis());
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

spring configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!--suppress SpringFacetInspection -->
<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">

    <!--
    Spring Configuration file
    bean Represent an object
    alias  alias
    import  Import an additional resource
    -->

    <bean id="user" class="com.kuang.pojo.User">
        <property name="name" value="qinjiang"/>
    </bean>

    <!--Assignment using constructor parameter Subscripts-->
    <bean id="user2" class="com.kuang.pojo.User">
        <constructor-arg index="0" value="kuangshen"/>
        <constructor-arg index="1" value="18"/>
    </bean>

    <!--Assignment by name-->
    <bean id="user3" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="kuangshen3"/>
        <constructor-arg name="age" value="3"/>
    </bean>

    <!--Assignment by type-->
    <bean id="user4" class="com.kuang.pojo.User">
        <constructor-arg type="java.lang.String" value="kuangshen4"/>
        <constructor-arg type="java.lang.Integer" value="18"/>
        <constructor-arg type="java.lang.String" value="male"/>
    </bean>


</beans>

Test class

package com.kuang.pojo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User)context.getBean("user");
        /*
        User user = new User();
        user.setName("qinjiang");
        */
        System.out.println(user.toString());
    }


    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user4");
        System.out.println(user);

    }



}

Summary:

  • Through parametric structure
    • By subscription
    • By parameter name [recommendation]
    • By parameter type
  • Through parametric structure
    • The default is constructed with no parameters

Note: There must be a parametric construction method.

For more information, check out: Create a factory model

6.Spring configuration file

bean

<! - Bean Explanation:
1. Without id and name, we can still get this object, but it is not recommended to use and need to use the class object of the class.
    User bean = context.getBean(User.class);

2.id is the name of the object
 3.class is the class to be instantiated
 4.name is an alias
    When there is an id, name is an alias. When there is no id, name is the name of the object.
    Aliases can be multiple
-->
<bean id="user" name="userTwo,user3" class="com.kuang.pojo.User">
    <property name="name" value="Spring"/>
</bean>

alias

<! - Alas explains:
1. name: the id of the bean object
 2,alias: an alias for an object
-->
<alias name="user" alias="user4"/>

import

<! - Import Explanation
 Function: Import another resource and load another configuration file
    classpath*: He'll go everywhere to find your files. [Low efficiency]
    Classpath: You can only find files in the classpath and report errors if you can't find them.
    File: Fill in the file path url [not recommended]
    http: Fill in the url of the network path [not recommended to use]
-->
<import resource="classpath*:userBeans.xml"/>
<import resource="classpath:userBeans.xml"/>
<import resource="file:"/>
<import resource="http:"/>

import is commonly used in team projects, where each person develops their own beans.xml and finally assembles it with a total file.

Keywords: Spring xml Java snapshot

Added by fekaduw on Tue, 30 Jul 2019 11:47:02 +0300