java learning stage 5 (SpringIoC&DI)

Keywords: Spring xml Java JDBC

0. framework 1

0.1 what is a framework?

Framework is a kind of combination of toolkits

We know that when I develop a function, if the function is more complex, we are likely to extract common things into tool classes, and if this tool class has many java tool classes to form a certain function, and the function is more powerful, we can make it into a jar package to be published for reference by other projects, which we can call framework

0.2 why framework?

When we study the black horse travel website, we write a lot of tool classes in bytes. For example, BaseServlet has two options,

A. Copy other people's code and use it directly, get off work early and enjoy a happy life

B. Work hard, stand on your own and give up the right to leave work at 6:00

Obviously, A person who is not too stubborn will choose A, because it is simple and convenient, and other people have already considered the issues we should consider

In the same way, the framework also extracts the common problems of the project and encapsulates them into tool classes for everyone to use. For the problems we encounter, the predecessors have helped us encapsulate the tool classes and use them

0.3 why are the three frameworks?

For the convenience of code management, layered development is now popular,

  1. The control layer is responsible for receiving parameters and responding to data

  2. The service layer is responsible for processing business logic

  3. dao layer is responsible for database interaction

But after the layering is completed, all java project developers around the world find that it's too troublesome to use servlet for all the logic in the control layer and dao layer, so they need to encapsulate tool classes. However, there are many encapsulated tool classes available on the Internet, so the developers will choose the more suitable ones,

There is no way in the world, and more people will be the way,

The three frameworks are called "three frameworks" because of the large number of users. However, there are still many frameworks in the market, but the number of employees is relatively small

What problems are solved by the three frameworks of 0.4?

  1. mybatis solves the problem of dao layer, which makes our access to database code more brief and faster

  2. Spring MVC solves the problem of presentation layer (web layer, also called controller layer), which makes our development simple and fast

  3. What spring solves is the integration of various frameworks, which is equivalent to a leader, who does not work and is only responsible for managing the previous relationship between people

[the external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-GmB8Rjgx-1583059037686)(assets/01 three-tier architecture. png))

Why is it more difficult to use 0.5 framework than not?

Why is it more difficult to use a framework than not? Isn't it that our development is simpler?

"How can I kill a chicken with a green dragon and Yan Moon knife"?

If you just log in and register, the traditional way, of course, is simple, but if you want to do a very large project, you must use the framework in the original way. Otherwise, the developed project may have many problems

So you start to learn that the project has such a feeling that the trouble of configuration is to lay a foundation for subsequent projects, which will make the development of subsequent projects easier?

1. spring overview

1.1 what is spring (understanding) IOC/AOP

Spring is a full stack lightweight open source framework for layered Java SE/EE applications, with IoC (Inverse Of Control) and AOP (Aspect Oriented Programming) as the core.

It provides many enterprise application technologies, such as the presentation layer spring MVC, the persistence layer spring JDBC template, and the business layer transaction management. It also integrates many famous third-party frameworks and class libraries in the open source world, and gradually becomes the most widely used Java EE enterprise application open-source framework

1.1 what problems has spring IOC solved? (Supplement)

/***
 * What is coupling?
 *      Dependencies between programs
 * How to decouple?
 *      Reduce dependencies between programs
        In actual development:
 *          It should be done: compile time does not depend, run time only depends.
 *
 * Train of thought?
 *      1)Use reflection to create objects instead of the new keyword.
 *      2)Get the fully qualified class name of the object to be created by reading the configuration file
 */

public class JDBCDemo {
    public static void main(String [] args) throws Exception{
        //1. Registration driver
        //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Class.forName("com.mysql.jdbc.Driver");
        //2. Get connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring","root","root");
        //3. Get preprocessing objects of operation database
        PreparedStatement pstm = conn.prepareStatement("select * from account");
        //4. Execute SQL to get result set
        ResultSet rs = pstm.executeQuery();
        //5. Traversal result set
        while(rs.next()){
            System.out.println(rs.getString("name"));
        }
        //6. Release resources
        rs.close();
        pstm.close();
        conn.close();
    }

The traditional code is coupled. How to reduce the coupling? We can write tool classes in bytes and use the idea of reflection to solve the problems we have encountered. The predecessors have already solved them. We can use them. This tool kit is spring, also called framework

UserService userService = new UserServiceImpl();
userService.save();

UserDao dao = new UserDaoImpl();
dao.save();

1.2 Spring development history (understanding)

EJB

Rod Johnson (father of Spring)

2017
The latest version of Spring, Spring 5.0, was released in September
General version (GA)

1.3 advantages of spring (understanding)

Easy decoupling and development

AOP programming support

Support for declarative transactions

Convenient program testing

1.4 Spring architecture (learn)

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-c43Trctu-1583059037692)(.\img \ picture 29.png))

2. spring quick start

2.1 Spring program development steps

① Import the basic package coordinates of Spring development

② Write Dao interface and implementation class

③ Create Spring core configuration file

④ Configure UserDaoImpl in the Spring configuration file

⑤ Get Bean instance using Spring's API

2.2 import the basic package coordinates of Spring development

<properties>
	<spring.version>5.0.5.RELEASE</spring.version>
</properties>
<!--Import spring Of context Coordinates context rely on core,beans,expression-->
<dependencies> 
    <dependency>  
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context</artifactId> 
        <version>${spring.version}</version>
    </dependency>
</dependencies>

2.3 write Dao interface and implementation class

public interface UserDao {  
    public void save();
}
public class UserDaoImpl implements UserDao {  
        @Override  
        public void save() {
        	System.out.println("UserDao save method running....");
	}
}

2.4 create Spring core configuration file

Create the applicationContext.xml configuration file under the classpath (resources)

<?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">
</beans>

2.5 configure UserDaoImpl in the Spring configuration file

<?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="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
    <bean id="userDao1" name="userDao2,userDao3" class="com.itheima.dao.UserDaoImpl"/>
</beans>

2.6 get Bean instance using Spring's API

@Test
public void test1(){
		ApplicationContext applicationContext = new  
             ClassPathXmlApplicationContext("applicationContext.xml");
             UserDao userDao = (UserDao) applicationContext.getBean("userDao");   				 userDao.save();
 }

2. Quick start analysis

2.1) IOC

What is IOC?

Above, the power to create an object is transferred to the framework or factory. The power to create an object is reversed. We call it reverse of control

What is?

​ spring IOC

spring has implemented the specific functions of the above IOC ideas. We call it springIOC. If Zhang San develops a framework by himself, we can call this framework zsIOC just a code
  IOC is the idea and springIOc is the concrete implementation

3. Spring configuration file

3.1 basic configuration of bean tag

The configuration object is created by Spring.

By default, it calls the parameterless constructor in the class. If there is no parameterless constructor, it cannot be created successfully.

Basic properties:

id: the unique id of the Bean instance in the Spring container

class: fully qualified name of Bean

3.2 single interest mode (Supplement)

What is the single interest model?

An object starts from tomcat to the end of tomcat (suppose it runs for 24 hours). If the object is created only once in the next period, the object is single interest

What are the benefits of simple interest?

	We know that every new object needs a part of memory to store the object. If an object needs a new one every time it is accessed, it wastes a lot of memory space, which leads to the performance degradation of the system
	Benefits of simple interest:
		1) Save memory
	Disadvantages:
		If there are global variables, there are security problems (in multithreaded environment)

How does java realize the single interest mode?

//Lazy and hungry
//The difference between the so-called "lazy" and "hungry" is the difference in the time of establishing a single object.
//"Lazy type" is to build this singleton object when you really use it:
public class Singleton{
    private Singleton(){}
    private static Singleton singleton = null;  //Do not create object
    public static synchronized Singleton getInstance(){		
             if(singleton == null) {        //Judge whether it is empty first                
                singleton = new Singleton ();  //Lazy way
             }
             return singleton ;
     }
}
// "Starving Han style" is to establish this single instance object at the beginning, no matter what you can't use:
public class Singleton{
    public Singleton(){}
    private static Singleton singleton = new Singleton();  //Establish object
    public static Singleton getInstance(){
        return singleton ;//Directly return singleton object    
}}

3.2 Bean label range configuration

Scope: refers to the scope of an object. The values are as follows:

Range of values Explain
singleton Default, singleton
prototype Multiple cases
request In the WEB project, Spring creates a Bean object and stores it in the request domain
session In the WEB project, Spring creates a Bean object and stores it in the session domain
global session In WEB projects, it is applied to the Portlet environment. If there is no Portlet environment, then the global session is equivalent to the session

1) When the scope value is singleton

Number of instantiations of Bean: 1

Instantiation time of Bean: when the Spring core file is loaded, instantiate the configured Bean instance

Bean's life cycle:

Object creation: when the application loads and creates a container, the object is created

Object running: the object is alive as long as the container is there

Object destroy: when the application is unloaded and the container is destroyed, the object is destroyed

2) When the scope value is prototype

Number of instantiations of Bean: multiple

When to instantiate a Bean: instantiate the Bean when the getBean() method is called

Object creation: creates a new object instance when using objects

Object running: live as long as the object is in use

Object destruction: when an object is not used for a long time, it is recycled by the Java garbage collector

3.3 Bean lifecycle configuration

Init method: Specifies the name of the initialization method in the class

Destroy method: Specifies the name of the destroy method in the class

3.4 three ways to instantiate a bean

1) Instantiation with nonparametric construction method

It will create class objects according to the default parameterless constructor. If there is no default parameterless constructor in the bean, it will fail to create

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>

2) Factory static method instantiation

Static method of factory returns Bean instance

public class StaticFactoryBean {
    public static UserDao createUserDao(){    
    return new UserDaoImpl();
    }
}
<bean id="userDao" class="com.itheima.factory.StaticFactoryBean" 
      factory-method="createUserDao" />
For example, create a conn object
<bean id="conn" class="java.sql.DriverManager" factory-method="getConnection">
    <constructor-arg name="url" value="jdbc:mysql://localhost:3306/spring"/>
</bean>

3) Factory instance method instantiation

Factory's nonstatic methods return Bean instances

public class DynamicFactoryBean {  
	public UserDao createUserDao(){        
		return new UserDaoImpl(); 
	}
}
<bean id="factoryBean" class="com.itheima.factory.DynamicFactoryBean"/>
<bean id="userDao" factory-bean="factoryBean" factory-method="createUserDao"/>

3.5 introduction to bean's dependency injection

DI : Dependency Injection

Dependency container, which manages the relationship between objects through injection

① Create UserService. UserService calls UserDao's save() method internally

public class UserServiceImpl implements UserService {
	@Override
	public void save() {
         ApplicationContext applicationContext = new 
                 ClassPathXmlApplicationContext("applicationContext.xml");       	           UserDao userDao = (UserDao) applicationContext.getBean("userDao");	
          userDao.save();
 	}
 }

② Give Spring permission to create UserServiceImpl

<bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>

③ Get UserService from Spring container for operation

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
userService.save();

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-9pkpkkrid-1583059037694) (assets / 156438341777. PNG))

3.6 Bean's concept of dependency injection

Dependent container injection object or data

Dependency Injection: it is the concrete implementation of the core IOC of Spring framework.

When writing the program, the creation of the object is handed over to Spring through inversion of control, but there is no possibility that there is no dependency in the code.

IOC decoupling only reduces their dependency, but does not eliminate it. For example, the business layer still calls the methods of the persistence layer.

After using Spring, the dependency between business layer and persistence layer will be maintained by Spring.

Simply put, it's just waiting for the framework to pass the persistence layer objects to the business layer, instead of getting them ourselves

3.7 Bean's dependency injection mode

① Construction method

Create a parametric construct

public class UserServiceImpl implements UserService {
	private UserDao userDao;
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;  
    } 
    @Override    
    public void save() {      
   		 userDao.save();
	}
 }

Configure Spring container to inject when calling with parameter construction

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">      		   	<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>

(2) set method

Add setUserDao method in UserServiceImpl

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;  
        } 
    @Override    
    public void save() {      
   		 userDao.save();
	}
}

Configure Spring container to call set method for injection

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
	<property name="userDao" ref="userDao"/>
</bean>

set method: P namespace injection

The essence of P namespace injection is also set method injection, but it is more convenient than the above set method injection, which is mainly reflected in the configuration file, as follows:

First, you need to introduce the P namespace:

xmlns:p="http://www.springframework.org/schema/p"

Secondly, the injection mode needs to be modified

<bean id="userService" class="com.itheima.service.impl.UserServiceImpl" 
      p:userDao-ref="userDao"/>

3.8 Bean's dependency injection data type

The above operations are all injected reference beans, where the object reference can be injected, common data types, collections, etc. can be injected in the container.

Three types of injected data

General data type

Reference data type

Collection data type

Among them, the reference data type will not be described here. The previous operations are to inject the reference of UserDao object. Next, take set method injection as an example to demonstrate the injection of common data type and set data type.

Bean's dependency injection data type

(1) Injection of common data types

public class UserDaoImpl implements UserDao {
private String company;
    private int age;
    public void setCompany(String company) {
        this.company = company;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void save() {
        System.out.println(company+"==="+age);
        System.out.println("UserDao save method running....");   
    }
}

<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property name="company" value="Intelligent Podcasting"></property>
    <property name="age" value="15"></property>
</bean>

(2) Injection of set data type (List)

public class UserDaoImpl implements UserDao {
	private List<String> strList;
	public void setStrList(List<String> strList) {
		this.strList = strList;
	}
	public void save() {
        System.out.println(strList);
        System.out.println("UserDao save method running....");
	}
}
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property name="strList">
        <list>
            <value>aaa</value>
            <value>bbb</value>
            <value>ccc</value>
        </list>
    </property>
</bean>

(3) Injection of set data type (List)

public class UserDaoImpl implements UserDao {
	private List<User> userList;
	public void setUserList(List<User> userList) {
	this.userList = userList;  
 }
public void save() {
	System.out.println(userList);
	System.out.println("UserDao save method running....");
	}
}
<bean id="u1" class="com.itheima.domain.User"/>
<bean id="u2" class="com.itheima.domain.User"/>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property name="userList">
        <list>
            <bean class="com.itheima.domain.User"/>
            <bean  class="com.itheima.domain.User"/>
            <ref bean="u1"/>
            <ref bean="u2"/>       
        </list>
    </property>
</bean>

(4) Injection of set data type (map < string, user >)

public class UserDaoImpl implements UserDao {
    private Map<String,User> userMap;
    public void setUserMap(Map<String, User> userMap) {
    this.userMap = userMap;
    }    
public void save() {      
	System.out.println(userMap);
	System.out.println("UserDao save method running....");
	}
}
<bean id="u1" class="com.itheima.domain.User"/>
<bean id="u2" class="com.itheima.domain.User"/>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property name="userMap">
        <map>            
            <entry key="user1" value-ref="u1"/>
            <entry key="user2" value-ref="u2"/>
        </map>
    </property>
</bean>

(5) Injection of collection data types (Properties)

public class UserDaoImpl implements UserDao {
    private Properties properties;
    public void setProperties(Properties properties) {
        this.properties = properties;
    }
	public void save() {
		System.out.println(properties);
		System.out.println("UserDao save method running....");
	}
}
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
    <property name="properties">
        <props>
            <prop key="p1">aaa</prop>
            <prop key="p2">bbb</prop> 
            <prop key="p3">ccc</prop>
        </props>
    </property>
</bean>

3.9 introduction of other configuration files (sub module development)

In the actual development, there are a lot of configuration contents in Spring, which leads to the complexity and large volume of Spring configuration. Therefore, some configurations can be disassembled into other configuration files, and the main Spring configuration file is loaded through the import tag

<import resource="applicationContext-xxx.xml"/>

4. spring related API

4.1 inheritance system of ApplicationContext

applicationContext: interface type, representing the application context. You can obtain the Bean object in the Spring container through its instance

4.2 implementation class of ApplicationContext

1)ClassPathXmlApplicationContext

It is recommended to load the configuration file from the root path of the class

2)FileSystemXmlApplicationContext

It loads the configuration file from the disk path, which can be anywhere on the disk.

3)AnnotationConfigApplicationContext

When using annotations to configure container objects, you need to use this class to create spring containers. It is used to read annotations.

4.3 use of getbean() method

public Object getBean(String name) throws BeansException {  
	assertBeanFactoryActive();   
	return getBeanFactory().getBean(name);
}
public <T> T getBean(Class<T> requiredType) throws BeansException {   			    	assertBeanFactoryActive();
	return getBeanFactory().getBean(requiredType);
}

Where, when the data type of the parameter is string, it means that the Bean instance is obtained from the container according to the Bean id, and the return is Object, which requires strong conversion.

When the data type of the parameter is Class, it means to match the Bean instance from the container according to the type. When there are multiple beans of the same type in the container, this method will report an error

getBean() method use

ApplicationContext applicationContext = new 
            ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userService");
  UserService userService2 = applicationContext.getBean(UserService.class);
72 original articles published, 59 praised, 3377 visited
Private letter follow

Posted by py343 on Sun, 01 Mar 2020 03:01:46 -0800