JAVA-4-[Spring framework] Bean management based on XML

1 Spring IOC container

(1) IOC underlying principle
(2) IOC interface (BeanFactory)
(3) IOC operation bean management (XML-based)
(4) IOC operation bean management (annotation-based)

1.1 IOC concept

(1) Inversion of Control (Inversion of Control), the creation of objects and the calling process between objects are handed over to Spring for management.
(2) The purpose of using IOC: to reduce the degree of coupling.
(3) The underlying principles of IOC: xml parsing, factory mode, reflection.
Factory pattern: reduce coupling.
Reflection: Get the bytecode file of the class.

1.2 The underlying principle of IOC

Call the method in the UserDao class in the UserService class.

class UserService{
    
    
	execute()
	{
    
    
		
	}
}

class UserDao{
    
    
	add()
	{
    
    
		...
	}
}

1.2.1 Original method (high coupling degree)

insert image description here

1.2.2 Factory mode (decoupling)

insert image description here

1.2.3 IOC process (minimum coupling degree)

insert image description here

1.3 IOC interface

1. The idea of ​​IOC is based on the IOC container, and the bottom layer of the IOC container is the object factory.
2. Spring provides two ways to implement the IOC container: (two interfaces)
(1) BeanFactory: The basic implementation of the IOC container is an interface used internally by Spring and is not provided for developers to use.
Objects are not created when a configuration file is loaded, they are created when an object is fetched or used.

(2) ApplicationContext: The sub-interface of the BeanFactory interface provides more powerful functions and is generally used by developers.
When the configuration file is loaded, all objects in the configuration file will be created.
3. Implementation classes in ApplicationContext
(1) FileSystemXmlApplicationContext
(2) ClassPathXmlApplicationContext

1.4 Bean management

1、什么是Bean管理
Bean管理指的是两个操作:
(1)Spring创建对象
(2)Spring注入属性
2、Bean管理操作有两种方式:
(1)基于xml配置文件方式实现
(2)基于注解方式实现

2 Based on the xml method

2.1 Creating objects

2.1.1 new method (original)

HellowWorld hello = new HelloWorld();

2.1.2 XML method (spring)

1、基于xml方式创建对象
<!--配置HellowWorld对象创建-->
<bean id="helloWorld123" class="HelloWorld"></bean>
(1)在spring配置文件中,使用bean标签,
标签里面添加对应属性,就可以实现对象创建。
(2)在bean标签中有很多属性
id属性:唯一标识。
class属性:类全路径(包名+类名)
name属性:与id属性功能相似,已不再使用。
(3)创建对象的时候,默认也是执行无参数构造方法

2.2 set method injection property

2、 基于xml方式注入属性
DI:依赖注入,就是注入属性
第一种注入方式:使用set方法进行注入
步骤:创建类,定义属性和对应的set方法
步骤:在spring的配置文件中进行配置。

第二种注入方式:使用有参数构造进行注入
步骤:创建类,定义属性,创建属性对应有参数构造方法。
步骤:在spring的配置文件中进行配置。

2.2.1 set method (original)


public class Book {
    
    
    //创建属性
    private String bname;
    private String bauthor;
    //创建属性对应的set方法

    public void setBname(String bname) {
    
    
        this.bname = bname;
    }

    public void setBauthor(String bauthor) {
    
    
        this.bauthor = bauthor;
    }

    public void getMessage(){
    
    
        System.out.println(bname+":"+bauthor);
    }

    public static void main(String[] args){
    
    
        // 使用时,先创建对象,再用set方法注入属性
        Book book = new Book();
        book.setBname("孔乙己");
        book.setBauthor("鲁迅");

        book.getMessage();
    }

}

2.2.2 XML mode (spring)

使用property完成属性注入
name:类里面属性名称
value:向属性注入的值

<bean id="book" class="Book">
        <property name="bname" value="孙子兵法" />
        <property name="bauthor" value="孙子" />
</bean>

How to use

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

public class zzz {
    
    
    public static void main(String[] args) {
    
    
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        // 2 获取配置创建的对象
        Book book = (Book) context.getBean("book");
        
        book.getMessage();
    }
}

2.3 Injection property with parameter construction

2、 基于xml方式注入属性
DI:依赖注入,就是注入属性
第一种注入方式:使用set方法进行注入
步骤:创建类,定义属性和对应的set方法
步骤:在spring的配置文件中进行配置。

第二种注入方式:使用有参数构造进行注入
步骤:创建类,定义属性,创建属性对应有参数构造方法。
步骤:在spring的配置文件中进行配置。

2.3.1 Construction method (original)

Right-click->Generate->Select to generate a parameterized structure
insert image description here

public class Orders {
    
    
	//创建属性
    private String oname;
    private String address;
    // 创建有参构造
    public Orders(String oname, String address) {
    
    
        this.oname = oname;
        this.address = address;
    }
    
    public void getMessage(){
    
    
        System.out.println(oname+":"+address);
    }
    public static void main(String[] args){
    
    
    	// 使用时
        Orders order = new Orders("lily","NewYork");
        order.getMessage();
    }
}

2.3.2 XML mode (spring)

<!--有参构造注入属性-->
<bean id="orders" class="Orders">
    <constructor-arg name="oname" value="lucy"/>
    <constructor-arg name="address" value="china"/>
</bean>

How to use

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

public class zzz {
    
    
    public static void main(String[] args) {
    
    
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        // 2 获取配置创建的对象
        Orders order = (Orders) context.getBean("orders");

        order.getMessage();
    }
}

2.4p namespace injection

(1)使用p名称空间注入,可以简化基于xml的set方法注入
第一步 添加p名称空间在配置文件中
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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-3.0.xsd">
   
第二步 进行属性注入,在bean标签中进行操作
<bean id="book" class="Book" p:bname="天龙八部" p:bauthor="金庸"></bean>

2.5 Injecting null and special characters

一、字面量
(1)null值
<bean id="book" class="Book">
    <property name="bname" value="孙子兵法" />
    <property name="bauthor">
        <null/>
    </property>
</bean>

输出如下:孙子兵法:null

(2)属性值包含特殊符号
方式一:把<>进行转移 &lt;&gt;
<bean id="book" class="Book">
    <property name="bname" value="孙子兵法" />
    <property name="bauthor" value="&lt;&lt;孙子&gt;&gt;"/>
</bean>
方式二:把带特殊符号内容写到CDATA
<bean id="book" class="Book">
    <property name="bname" value="孙子兵法" />
    <property name="bauthor">
        <value><![CDATA[<<老子>>]]></value>
    </property>
</bean>

2.6 Injecting external beans

web layer, service layer, dao layer.

2、注入属性-外部bean
(1)创建两个类service类和dao类
(2)在service中调用dao
(3)在spring配置文件中配置

2.6.1 Original way

1. Dao layer interface
code file UserDao.java

package dao;

public interface UserDao {
    
    
    public void update();
}

2. Dao layer interface implementation
code file UserDaoImpl.java

package dao;

public class UserDaoImpl implements UserDao{
    
    

    @Override
    public void update() {
    
    
        System.out.println("dao update ......");
    }
}

3. Service layer
code file UserService.java

package service;

import dao.UserDao;
import dao.UserDaoImpl;

public class UserService {
    
    
    public void add(){
    
    
        System.out.println("service add ......");

        // 在service层中调用Dao层
        // 创建UserDao对象
        UserDao userdao = new UserDaoImpl();
        userdao.update();
    }
    public static void main(String[] args) {
    
    
        UserService userservice = new UserService();
        userservice.add();
    }
}

2.6.2 XML method

1. Dao layer interface
code file UserDao.java
2. Dao layer interface implementation
code file UserDaoImpl.java
3. service layer
code file UserService.java

package service;

import dao.UserDao;

public class UserService {
    
    
    //创建UserDao类型属性,生成set方法
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
    
    
        this.userDao = userDao;
    }

    public void add(){
    
    
        System.out.println("service add ......");
        // 调用dao层
        userDao.update();
    }
}

Four, beans.xml configuration file

<!-- 1 service和dao对象创建-->
<bean id="userservice123" class="service.UserService">
    <!--注入userDao对象
        name属性:类里面的属性名称
        ref属性:创建userDao对象bean标签id值
    -->
    <property name="userDao" ref="userDaoImpl123"/>
</bean>
<bean id="userDaoImpl123" class="dao.UserDaoImpl"></bean>

5. Test use

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;

public class zzz {
    
    
    public static void main(String[] args) {
    
    
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        // 2 获取配置创建的对象
        UserService userservice = (UserService) context.getBean("userservice123");
        userservice.add();
    }
}

2.7 Injecting inner beans

(1)一对多关系:部门和员工
一个部门有多个员工,一个员工属于一个部门
(2)在实体类间表示一对多关系,员工所属部门,使用对象类型属性表示

1. Dept.java

//部门类
public class Dept {
    
    
    private String dname;
    public void setDname(String dname) {
    
    
        this.dname = dname;
    }
    public String getDname() {
    
    
        return dname;
    }
}

2. Emp.java

//员工类
public class Emp {
    
    
    private String ename;
    private String gender;
    //员工属于某一个部门,使用对象类型属性表示
    private Dept dept;
    public void setDept(Dept dept) {
    
    
        this.dept = dept;
    }

    public void setEname(String ename) {
    
    
        this.ename = ename;
    }

    public void setGender(String gender) {
    
    
        this.gender = gender;
    }
    
    public void getMessage(){
    
    
        System.out.println(ename+":"+gender+":"+dept);
    }
}

Three, beans.xml configuration file

<!--内部bean-->
<bean id="emp" class="Emp">
    <!--设置两个普通属性-->
    <property name="ename" value="lily"/>
    <property name="gender" value="女"/>
    <!--设置对象类型属性-->
    <property name="dept">
        <bean id="dept" class="Dept">
            <property name="dname" value="人力资源部"/>
        </bean>
    </property>
</bean>

4. Test

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


public class zzz {
    
    
    public static void main(String[] args) {
    
    
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        // 2 获取配置创建的对象
        Emp emp = (Emp) context.getBean("emp");
        emp.getMessage();
    }
}

2.8 Cascade assignment

(1)第一种写法:
<!--级联赋值-->
<bean id="emp" class="Emp">
    <!--设置两个普通属性-->
    <property name="ename" value="lily"/>
    <property name="gender" value="女"/>
    <!--级联赋值-->
    <property name="dept" ref="dept12"/>
</bean>
<bean id="dept12" class="Dept">
    <property name="dname" value="人力资源部"/>
</bean>

(2)第二种方法
<!--级联赋值-->
<bean id="emp" class="Emp">
    <!--设置两个普通属性-->
    <property name="ename" value="lily"/>
    <property name="gender" value="女"/>
    <!--级联赋值-->
    <property name="dept" ref="dept12"/>
    <property name="dept.dname" value="技术部"/>
</bean>
<bean id="dept12" class="Dept">
    <property name="dname" value="人力资源部"/>
</bean>

The second method requires attention:
insert image description here

3 Spring IoC container

IoC (Inverse of Control) inversion of control.
IoC refers to handing over the creation right of objects to Spring to create. Before using Spring, the creation of objects is created by us using new, but after using Spring, the creation of objects is handed over to the Spring framework.

The IoC container is the core of Spring and can also be called the Spring container. Spring uses the IoC container to manage the instantiation and initialization of objects, as well as the entire life cycle of objects from creation to destruction.

The objects used in Spring are all managed by the IoC container, and we don't need to manually use the new operator to create objects. The objects managed by the IoC container are called Spring Beans, and Spring Beans are Java objects, which are no different from objects created using the new operator.

Spring obtains which objects need to be instantiated by reading information in XML or Java annotations .

Spring provides two different types of IoC containers, BeanFactory and ApplicationContext containers.

3.1 BeanFactory container

BeanFactory is the simplest container, defined by org.springframework.beans.factory.BeanFactory interface, using lazy loading (lazy-load), so the container starts faster.

BeanFactory provides the most basic functions of the container.

In order to be compatible with third-party frameworks integrated by Spring (such as BeanFactoryAware, InitializingBean, DisposableBean), this interface is still reserved.

To put it simply, BeanFactory is a factory that manages beans. It is mainly responsible for initializing various beans and calling their life cycle methods.

BeanFactory 接口有多个实现类,
最常见的是org.springframework.beans.factory.xml.XmlBeanFactory。
使用BeanFactory需要创建XmlBeanFactory类的实例,
通过XmlBeanFactory类的构造函数来传递Resource对象。如下所示。
Resource resource = new ClassPathResource("Beans.xml"); 
BeanFactory factory = new XmlBeanFactory(resource);  

MainApp.java file

package net.biancheng;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class MainApp {
    
    
    public static void main(String[] args) {
    
    
        Resource resource = new ClassPathResource("Beans.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        HelloWorld obj = (HelloWorld) factory.getBean("helloWorld123");
        obj.getMessage();
    }
}

In the main program, you need to pay attention to the following two points:
(1) The first step is to use the XmlBeanFactory() API provided by the framework to generate factory beans and use the ClassPathResource() API to load the bean configuration files available under the path CLASSPATH. The XmlBeanFactory() API is responsible for creating and initializing all objects, namely beans mentioned in the configuration file.

(2) The second step uses the getBean() method of the bean factory object generated in the first step to obtain the required bean. This method returns a real object by the bean ID in the configuration file, which can finally be used for the actual object. Once you get this object, you can use this object to call any method.
Later this XmlBeanFactory class was abolished.

3.2 ApplicationContext container

ApplicationContext inherits the BeanFactory interface, defined by the org.springframework.context.ApplicationContext interface, and the object is loaded when the container is started. ApplicationContext adds many enterprise-level functions on the basis of BeanFactory, such as AOP, internationalization, event support, etc.

The ApplicationContext interface has two commonly used implementation classes, as follows.
(1) ClassPathXmlApplicationContext
This class searches for the specified XML configuration file from the class path ClassPath, and completes the instantiation of ApplicationContext, as shown below.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(String configLocation);

In the above code, the configLocation parameter is used to specify the name and location of the Spring configuration file, such as Beans.xml.
(2) FileSystemXmlApplicationContext
This class searches for the specified XML configuration file from the specified file system path, and completes the instantiation of ApplicationContext, as shown below.

ApplicationContext applicationContext = new FileSystemXmlApplicationContext(String configLocation);

The difference between it and ClassPathXmlApplicationContext is: when reading the Spring configuration file, FileSystemXmlApplicationContext will not read the configuration file from the class path, but specify the location of the configuration file through parameters. That is, FileSystemXmlApplicationContext can obtain resources outside the class path, such as "F:/workspaces/Beans.xml".

Guess you like

Origin blog.csdn.net/qq_20466211/article/details/129645403