(1) Spring study notes (IOC operation Bean management)

IOC 

1.IOC

Inversion of control. Reduce the coupling between codes (purpose). The most common way is called dependency injection.

2. The underlying principle of IOC

(1) xml parsing, factory pattern, reflection

Factory pattern:

 

IOC process:

(1) xml configuration file. Objects created by configuration

(2) There are service classes and dao classes, and create factory classes

class UserFactory{
  public static UserDao getDao(){
    String classValue = class属性值;	//xml解析
    Class clazz = Class.forName(classValue);// 通过反射创建对象
    return (UserDao)clazz.newInstance();
  }
}

Further reduce coupling.

IOC thoughts:

(1) It is completed based on the IOC container, and the bottom layer of the IOC container is the object factory.

(2) Spring provides IOC container implementation in two ways, two interfaces

a. 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 loading configuration files

b. ApplicationContext : A sub-interface of the BeanFactory interface, which provides more powerful functions and is generally used by developers.

When the configuration file is loaded, it will be created in the configuration file object

IOC operation bean management:

(0) Bean management refers to two operations

- Spring creates objects

- Spring injected properties

Bean management operates in two ways:

(1) Realized based on xml configuration file

(2) Based on annotations

Create objects based on xml:

(1)

(2) The bean tag has many attributes.

  • id: unique attribute

  • class: class full path (package class path)

  • name

(3) When creating an object, the default is to execute the no-argument construction method to complete the object creation

Inject attributes based on xml:

(1) DI: Dependency Injection, which is to inject properties.

The first injection method: use the set method to inject

package com.demo.spring5.testdemo;


public class Book {
    private String bname;

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

    public static void main(String[] args) {
        Book book = new Book();
      book.setBname("abc");
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

    <!--peizhiUser-->
    <bean id="user" class="com.demo.spring5.User"/>
    <bean id="book" class="com.demo.spring5.Book">

        <!--使用property注入-->
        <!--name:类型名称-->
        <!--value:注入的值-->
        <property name = "bname" value="三国演义"/>
        <property name = "bauthor" value="罗贯中"/>
    </bean>
</beans>

The second way: use parameterized construction for injection

public class Orders {
    private String oname;
    private String address;

    public Orders(String oname, String address) {
        this.oname = oname;
        this.address = address;
    }
    
}

 bean.xml configuration

    <bean id="orders" class="com.demo.spring5.Orders">
        <constructor-arg name="oname" value="abc"/>
        <constructor-arg name="address" value="beijing"/>
    </bean>

You can also use the index

<constructor-arg index="0" value="beijing"/>

 test:

@Test
public void testOrder(){
  ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
  Orders order = context.getBean("orders", Orders.class);

  System.out.println(order);
  order.test();
}

p namespace injection:

(1) Add the p namespace in the configuration file

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

<bean id="book" class="com.demo.spring5.Book" p:bname="三国演义" p:bauthor="罗贯中">

</bean>

IOC operation Bean management (xml injection into other types of attributes)

(1) Literal amount

  • null value:

<property name="address"><null/>
</property>
  • Attribute values ​​contain special symbols:

Inject property - external bean :

(1) Create two classes service class and dao class

(2) Call the method in dao in service

(3) Found in the spring configuration file

package com.demo.spring5.dao;

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

}
package com.demo.spring5.service;

import com.demo.spring5.dao.userDao;
import com.demo.spring5.dao.userDaoImpl;

@SuppressWarnings("all")
public class userService {
    //创建userDao类型属性,生成set方法
    private userDao userDao;

    public void setUserDao(userDao userDao) {
        this.userDao = userDao;
    }

    public void add(){
        System.out.println("service add...");
        userDao.update();

        // 创建对象
//        userDaoImpl userDao = new userDaoImpl();
//        userDao.update();

    }
}

test:

public class TestBean {

    @Test
    public void testAdd(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        userService userService = context.getBean("userService", userService.class);
        System.out.println(userService);
        userService.add();

    }
}
 <!--service对象和dao对象创建-->
    <bean id="userService" class="com.demo.spring5.service.userService">
        <!--注入userDao对象
            name属性值:类里面属性名称
            ref属性:创建userDao对象bean标签id值
        -->
        <property name="userDao" ref="userDaoImpl"/>
</bean>
    <bean id="userDaoImpl" class="com.demo.spring5.dao.userDaoImpl"/>

Injecting properties - inner beans and cascading assignments:

(1) One-to-many: department and employee

(2) A one-to-many relationship is represented between entity classes, and employees represent their departments. Applicable object type properties for representation.

package com.demo.spring5.bean;

public class employee {
    private String ename;
    private String gender;

    private department dept;

    public void setDept(department dept) {
        this.dept = dept;
    }

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

    public void setGender(String gender) {
        this.gender = gender;
    }
}

package com.demo.spring5.bean;

public class department {

    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }
}

(3) Configure in the spring configuration file

    <bean id="emp" class="com.demo.spring5.bean.employee">
        <!--先设置两个普通属性-->
        <property name="ename" value="lucy"/>
        <property name="gender" value="女"/>
        <!--设置对象类型属性-->
        <property name="dept">
            <bean id="dept" class="com.demo.spring5.bean.department">
                <property name="dname" value="安保部"/>
            </bean>
        </property>
    </bean>

Injecting properties - cascading assignments

(1) The first way of writing

    <bean id="emp" class="com.demo.spring5.bean.employee">
    <!--先设置两个普通属性-->
    <property name="ename" value="lucy"/>
    <property name="gender" value="女"/>
        <!--级联赋值-->
    <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.demo.spring5.bean.department">
        <property name="dname" value="财务部"></property>
    </bean>

(2) The second way of writing

The get method that needs to generate dept

    <bean id="emp" class="com.demo.spring5.bean.employee">
    <!--先设置两个普通属性-->
    <property name="ename" value="lucy"/>
    <property name="gender" value="女"/>
        <!--级联赋值-->
    <property name="dept" ref="dept"></property>
      <property name="dept.dname" value="技术部"></property>
    </bean>
    <bean id="dept" class="com.demo.spring5.bean.department">
        <property name="dname" value="财务部"></property>
    </bean>

IOC operation Bean management (xml management injection collection attributes)

1. Inject array type properties :

2. Inject the List collection type property:

3. Inject the Map collection type property:

(1) Create a class

package com.demo.collectiontype;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Stu {
    private String[] courses;

    private List<String> list;

    private Map<String,String> maps;

    private Set<String> set;

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public void setCourses(String[] courses) {
        this.courses = courses;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
}

(2) Configuration file in spring

<!--集合类型属性注入-->
    <bean id="stu" class="com.demo.collectiontype.Stu">
        <!--数组类型注入-->
        <property name="courses">
            <array>
                <value>java</value>
                <value>mysql</value>
            </array>
        </property>
        
        <!--list-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>小三</value>
            </list>
        </property>       
        
        <!--map-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PYTHON" value="python"></entry>
            </map>
        </property>
        
        <!--set-->
        <property name="set">
            <set>
                <value>111</value>
                <value>222</value>
            </set>
        </property>
    </bean>
</beans>

4. Set the object type value in the collection

    <!--注入list集合类型,值是对象-->
    <property name="courseList">
        <list>
            <ref bean="course1"></ref>
            <ref bean="course2"></ref>
        </list>
    </property>
</bean>
<!--创建多个course对象-->
<bean id="course1" class="com.demo.collectiontype.Course">
    <property name="cname" value="test1"></property>
</bean>
<bean id="course2" class="com.demo.collectiontype.Course">
    <property name="cname" value="test2"></property>
</bean>

5. Extract the collection injection part

(1) Introduce the namespace util 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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util.xsd">

IOC operation Bean management (FactoryBean):

1. Spring has two types of beans, a common bean, and a factory bean.

2. Ordinary bean: the bean type in the configuration file is the return type

3. Factory bean: The bean type defined in the configuration file can be different from the return type

The first step: Create a class, let this class be a factory bean, and implement the interface FactoryBean

Step 2: Implement the method in the interface, and define the returned bean type in the implemented method

<bean id="myBean" class="com.demo.factorybean.Mybean">
  </bean>
  
@Test
  public void test3(){
  	ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
  Course course = context.getBean("myBean", Course.class);
  System.out.println(course);
}

IOC operation bean management (bean scope)

1. In Spring, set whether to create a bean instance as a single instance or multiple instances

2. In Spring Li Min, by default, the bean is a single instance object

3. How to set single instance or multiple instances

(1) In the bean tag of the spring configuration file, there is an attribute (scope) to set single instance or multiple instances

(2) scope attribute value

The default value of the first value, singleton, means a single instance object

The second value prototype multi-instance

(3) The difference between singleton and prototype

Set scope=singleton, and a single instance object will be created when the spring configuration file is loaded

Set scope=prototype, instead of creating an object when loading the spring configuration file, create a multi-instance object when calling the getBean method.

request

session

IOC operation Bean management (bean life cycle )

1. Life cycle

(1) The process from object creation to object destruction

2. bean life cycle

(1) Create a bean instance through the constructor (no parameter construction)

(2) Set values ​​for bean properties and drink other beans (call the set method)

Method for passing bean instances to bean post-processors

(3) Call the initialization method of the bean (need to configure the initialization method)

Method for passing bean instances to bean post-processors

(4) The bean is ready to use (the object is obtained)

(5) When the container is closed, call the bean's destruction method (configuration is required)

IOC operation Bean management (xml automatic assembly)

According to the specified assembly rules (property name or property type), Spring automatically injects the matching property value.

<!--实现自动装配
    bean标签属性autowire,配置自动装配
    autowire属性常用两个值:
        byName根据属性名称注入,注入值的bean的id值和类属性名称一样
        byType根据属性类型注入-->
    <bean id="emp" class="com.demo.autowire.Emp" autowire="byName">

IOC operation bean management (external properties file)

1. Directly configure database information

(1) Configure druid connection pool

(2) Introducing the druid connection pool depends on the jar package

2. Introduce an external property file to configure the database connection pool

(1) Create external property files, properties format files, and database information

(2) Introduce the external properties property file into the spring configuration file

Introduce the context namespace

Guess you like

Origin blog.csdn.net/weixin_44516623/article/details/127836412