Spring5 from entry to grave 01

Posted by NSW42 on Thu, 27 Jan 2022 16:03:34 +0100

Spring framework overview

Spring makes it easy to create Java enterprise applications. It provides everything needed to use the Java language in the enterprise environment, supports Groovy and Kotlin as alternative languages on the JVM, and can flexibly create a variety of architectures according to the needs of applications. Starting with Spring Framework 5.0, spring needs JDK 8(Java SE 8), and has provided ready-made support for JDK 9.

Spring supports a wide range of application scenarios. In large enterprises, applications usually exist for a long time and must run on JDK and application servers whose upgrade cycle is not controlled by developers. Other servers can run as a single jar, and servers can be embedded in the cloud environment. Others may be stand-alone applications that do not require a server (such as batch or integration workloads). Spring is open source. It has a large and active community that can provide continuous feedback according to various actual use cases. This helped spring develop successfully for a long time.

Each module (or component) that makes up the Spring framework can exist alone or be implemented jointly with one or more other modules.

The functions of each module are as follows:

Core container: the core container provides the basic functions of the Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the control flip (IOC) pattern to separate the configuration and dependency specifications of the application from the hard application code

Spring context: a spring context is a configuration file that provides context information to the spring framework. The spring context includes enterprise services such as JNDI, EJB e-mail, internationalization, validation, and scheduling capabilities.

Spring DAO: the JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code that needs to be written (such as opening and closing connections). The JDBC oriented exceptions of spring DAO follow the general DAO exception hierarchy


Spring AOP: through the configuration management feature, the spring AOP module directly integrates the aspect oriented programming functions into the spring framework. Therefore, you can easily make the spring framework manage any object that supports AOP. The 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 components.

Spring ORM: the spring framework inserts several "ORM" frameworks to provide object relationship tools for "ORM", including "JDO", "Hibernate" and "iBatis" SQL "Map. All of this follows the common transaction and DAO exception hierarchies of spring.
Spring Web context module: the Web context module is built on the application context module and provides context for applications based on spring web. Therefore, the spring framework supports integration with Jakarta Struts. The web} module also simplifies processing multipart requests and binding request parameters to domain objects.
Spring MVC framework: the MVC framework is a fully functional MVC implementation for building Web applications. Through the policy interface, the MVC # framework becomes highly configurable. MVC # accommodates a large number of view technologies, including # JSP, Velocity, Tiles, iText # and # POI.
Spring Web context module: the Web context module is built on the application context module and provides context for applications based on spring web. Therefore, the spring framework supports integration with Jakarta Struts. The web} module also simplifies processing multipart requests and binding request parameters to domain objects.
Spring MVC framework: the MVC framework is a fully functional MVC implementation for building Web applications. Through the policy interface, the MVC # framework becomes highly configurable. MVC # accommodates a large number of view technologies, including # JSP, Velocity, Tiles, iText # and # POI.

IOC Foundation

1. First write a UserDao interface:

public interface UserDao {
    public  void getUser();
}

2. Then write the implementation class of DAO

public class UserDaoImpl implements UserDao {

    public void getUser() {
        System.out.println("Get user data");
    }
}

3. Then write the UserService interface

public  interface UserService {
     public  void getUser();
}

4. Finally, write the implementation class of Service

public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoImpl();

    public void getUser() {
        userDao.getUser();
    }
}

5. Test it

@Test
    public void test(){
      UserService service=new UserServicelmpl();
       service.getUser();
}

This is our original way. At first, everyone wrote it like this, right Let's revise it now

Add an implementation class of Userdao
 

public class UserDaoMySqlImpl implements UserDao {
   @Override
   public void getUser() {
       System.out.println("MySql Get user data");
  }
}


Next, if we want to use MySql, we need to modify the corresponding implementation in the service implementation class
 

public class UserServiceImpl implements UserService {
   private UserDao userDao = new UserDaoMySqlImpl();

   @Override
   public void getUser() {
       userDao.getUser();
  }
}


In the assumption, we add another implementation class of Userdao
 

public class UserDaoOracleImpl implements UserDao {
   @Override
   public void getUser() {
       System.out.println("Oracle Get user data");
  }
}


If we want to use Oracle, we need to modify the corresponding implementation in the service implementation class Assuming that our demand is very large, this method is not applicable at all, even anti-human. Right? Every change requires a lot of code modification The coupling of this design is too high, which will affect the whole body

How can we solve it?  

Where we need to use it, we can leave an interface instead of implementing it. Using set, we can modify it in the code
 

public class UserServiceImpl implements UserService {
   private UserDao userDao;
// Using set to realize
   public void setUserDao(UserDao userDao) {
       this.userDao = userDao;
  }

   @Override
   public void getUser() {
       userDao.getUser();
  }
}


Now go to our test class and test;
 

@Test
public void test(){
   UserServiceImpl service = new UserServiceImpl();
   service.setUserDao( new UserDaoMySqlImpl() );
   service.getUser();
   //So now we want to use Oracle to implement it
   service.setUserDao( new UserDaoOracleImpl() );
   service.getUser();
}


ICO essence


Inversion of control (IoC) is a design idea. DI (dependency injection) is a method to realize IoC. Some people think that DI is just another term of IoC. In programs without IoC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded. In programs, the creation of objects is controlled by the program itself. After control reversal, the creation of objects is transferred to a third party. Personally, I think the so-called control reversal is that the way to obtain dependent objects is reversed.
IoC is the core content of the Spring framework. It is perfectly implemented in many ways. You can use XML configuration or annotation. The new version of Spring can also realize IoC with zero configuration.
During initialization, the Spring container reads the configuration file first, creates and organizes objects according to the configuration file or metadata, and stores them in the container. When the program is used, it takes out the required objects from the Ioc container.
When configuring beans in XML, the definition information of beans is separated from the implementation, and the annotation method can integrate the two. The definition information of beans is directly defined in the implementation class in the form of annotation, so as to achieve the purpose of zero configuration.
Inversion of control is a way to produce or obtain specific objects through description (XML or annotation) and through a third party. In Spring, the IoC container implements control inversion, and its implementation method is Dependency injection (DI).


HelloSpring

Import Jar package
Note: spring} needs to import commons logging for logging We use maven, which will automatically download the corresponding dependencies
 

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>


Write code
1. Write a Hello entity class

public class Hello {
   private String name;

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

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



2. Write our spring file, here we name it beans xml
 

<?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 namely java object , from Spring Create and manage-->
   <bean id="hello" class="com.kuang.pojo.Hello">
       <property name="name" value="Spring"/>
   </bean>

</beans>


3. We can go and test it
 

@Test
public void test(){
   //Parse beans XML file to generate and manage the corresponding Bean object
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //getBean: the parameter is the id of the bean in the spring configuration file
   Hello hello = (Hello) context.getBean("hello");
   hello.show();
}


reflection
hello, who created the object? The hello object is created by Spring

How are the properties of the Hello} object set? The properties of the Hello object are set by the Spring container

This process is called control reversal:

Control: who controls the creation of objects? The objects of traditional applications are created by the program itself. After using Spring, the objects are created by Spring

Inversion: the program itself does not create an object, but becomes a passive receiving object

Dependency injection: it uses the set method to inject

IOC is a programming idea, which changes from active programming to passive reception

You can browse the underlying source code through newClassPathXmlApplicationContext

Modify case 1
In case 1, we add a Spring configuration file beans xml
 

<?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 id="MysqlImpl" class="com.kuang.dao.impl.UserDaoMySqlImpl"/>
   <bean id="OracleImpl" class="com.kuang.dao.impl.UserDaoOracleImpl"/>

   <bean id="ServiceImpl" class="com.kuang.service.impl.UserServiceImpl">
       <!--be careful: there name Not an attribute , But set The part behind the method , Initial lowercase-->
       <!--Reference another bean , Not use value But with ref-->
       <property name="userDao" ref="OracleImpl"/>
   </bean>

</beans>

Test!

@Test
public void test2(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");
   serviceImpl.getUser();
}

OK, now, we don't need to change it in the program. To realize different operations, we only need to modify it in the xml configuration file. The so-called IoC is done in one sentence: the objects are created, managed and assembled by Spring \!  


IOC object creation method

Through nonparametric construction

1,User.java

public class User {

   private String name;

   public User() {
       System.out.println("user Nonparametric construction method");
  }

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

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

}

2,beans.xml

<?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 id="user" class="com.kuang.pojo.User">
       <property name="name" value="kuangshen"/>
   </bean>

</beans>

3. Test class

@Test
public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //When the getBean is executed, the user has been created and constructed without parameters
   User user = (User) context.getBean("user");
   //Call the method of the object
   user.show();
}

As a result, it can be found that the User object has been initialized through parameterless construction before calling the show method!

Created by parametric construction method

1,UserT . java

public class UserT {

   private String name;

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

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

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

}

2,beans.xml} can be written in three ways

<!-- First basis index Parameter subscript setting -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <!-- index Refers to the construction method , Subscript starts at 0 -->
   <constructor-arg index="0" value="kuangshen2"/>
</bean>
<!-- The second is set according to the parameter name -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <!-- name Refers to the parameter name -->
   <constructor-arg name="name" value="kuangshen2"/>
</bean>
<!-- The third one is set according to the parameter type -->
<bean id="userT" class="com.kuang.pojo.UserT">
   <constructor-arg type="java.lang.String" value="kuangshen2"/>
</bean>

3. Testing

@Test
public void testT(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   UserT user = (UserT) context.getBean("userT");
   user.show();
}

Conclusion: when the configuration file is loaded. The managed objects have been initialized!
Spring configuration

alias
Alias # set an alias for a bean. You can set multiple aliases

<!--Setting alias: getting Bean You can use alias to get-->
<alias name="userT" alias="userNew"/>
Bean Configuration of
<!--bean namely java object,from Spring Create and manage-->

<!--
   id yes bean Identifier of,To be unique,If not configured id,name Is the default identifier
   If configured id,Configured again name,that name It's an alias
   name You can set multiple aliases,You can use commas,semicolon,Space separated
   If not configured id and name,Can be based on applicationContext.getBean(.class)Get object;

class yes bean Fully qualified name of=Package name+Class name
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.kuang.pojo.Hello">
   <property name="name" value="Spring"/>
</bean>

Topics: Java Spring Spring Boot SSM