Advanced features of SpringIoC components

Table of contents

1. Cycle and scope of Bean components

2. FactoryBean interface


1. Cycle and scope of Bean components

1.1 Life cycle of Bean components

What are Bean's periodic methods

  1. We can define methods in the component class and then call them when the IoC container instantiates and destroys the component object! These two methods we become life cycle methods!
  2. Similar to Servlet's init/service/destroy method, we can complete initialization and release resources in the periodic method.
  3. Bean has only two cycles, init and destroy, that is, initialization and destruction.

1.2 Code implementation of Bean life cycle
Create component class:

package com.alphamilk.Ioc5;

public class JavaBean {
    /*
    注意:使用周期方法时候,对应的方法必须满足以下几点
    1.无参
    2.返回值类型为void
     */
    public void init(){
        System.out.println("javaBean被初始化");
    }
    public  void destory(){
        System.out.println("JavaBean被正常销毁");
    }
}

Create the corresponding configuration file 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">

<!--    组件创建前面都是一样的,但是需要加上对应的周期方法:
        1.init-method 初始化组件方法 
        2.destroy-method 销毁组件方法
-->
    <bean id="javaBean" class="com.alphamilk.Ioc5.JavaBean" init-method="init" destroy-method="destory"/>
</beans>

 test:

package com.alphamilk.Ioc;


import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class newTest {
    @Test
    public void test(){
//        创建容器对象
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("springioc-5.xml");
        /*
        注意,如果没有使用close函数,则会出现destroy方法无法调用的情况
        因为没有close下,ioc容器会意外死亡,就不会调用destroy方法
         */
//        正常销毁组件对象
        applicationContext.close();
    }
}


2.1 Scope of Bean tags

What is the scope of Bean tag

Generally speaking, the scope of Bean corresponds to two forms, single instance and multiple instances. The following explains the single instance and multiple instances in detail.

  • Singleton: Generally, the singleton mode is used by default when creating beans. This means that if there is only one corresponding Bean label when gettingBean in the test class, then even if getBean returns multiple times, the returned object will be the same.
  • Multiple instances: refers to when using the getBean method in the test class. Although there is only one label, each call will generate a new Bean component object.

The specific number of Bean instance objects created is specified by the Scope property of the Bean! It is generally recommended to use singleton mode

 2.2 Scope optional values

value meaning When to create an object default value
singleton In the IOC container, the object of this bean is always a single instance When the IOC container is initialized yes
prototype This bean has multiple instances in the IOC container When getting a bean no

It is special in WebApplicationContext. Its scope has two more values.

value meaning When to create an object default value
request A valid instance within the request scope per request no
session Instances valid within the session scope per session no

2.3 Case code

Create component class object

package com.alphamilk.Ioc5;

public class JavaBeanScope {
    public void doWork(){
        System.out.println("JavaBean is Working");
    }
}

Configuration corresponding to single case and multiple cases

There is no need to configure scpoe by default

Test code:

package com.alphamilk.Ioc;

import com.alphamilk.Ioc5.JavaBeanScope;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class newTest {
    @Test
    public void test(){
//        创建Ioc容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springioc-5.xml");
//        通过容器获取Bean对象
        JavaBeanScope bean = applicationContext.getBean(JavaBeanScope.class);
        JavaBeanScope bean2 = applicationContext.getBean(JavaBeanScope.class);

//        结果为False,因为采用多例模式下,每一次getBean,Ioc都会new一个新的JavaBeanScope对象
        System.out.println(bean==bean2);
    }
}


2. FactoryBean interface

1.1 What is FactoryBean

  1. As mentioned in our previous article, there are two interfaces and four implementation classes to implement SpringIoc. Factory is the parent interface of the two interfaces.
  2. Although the Ioc container will automatically create a new object, not all components can be created casually, such as Mybatis. The final step is to construct the Session operation database object, and to obtain the object, you need to first obtain the configuration information getResource (configuration file), then construct the SessionFactoryBuilder, and then call the SessionFactoryBuilder function Builder. The finally obtained SessionFactory also needs to call the method openSession. This complex object creation process cannot be implemented by a general Ioc container. So we set how to instantiate the object directly from its root FactoryBean.

Modify complex instantiation ideas:

1.2 Common methods of FactoryBean interface

method name Method description
T getObject() Returns an object instance created by the factory. The return value will be stored in the IoC container.
boolean isSingleton() Returns if this FactoryBeanreturns a singleton object true, otherwise false. The default implementation is returned true(note that using the lombok plug-in may affect the effect).
Class<?> getObjectType() Returns getObject()The type of object returned by the method. Returned if the object type is not known before creation null.

1.3 Implement FactoryBean case code

1. Create a subclass of JavaBean that needs to be instantiated

package com.alphamilk.Ioc6;

public class JavaBean {
    private String name;
    private int age;

//    组件方法
    public void PrintInfo(){
        System.out.println(name+"的年龄是"+age);
    }
}

2. Create a factory class that needs to be instantiated by JavaBean

package com.alphamilk.Ioc6;

import org.springframework.beans.factory.FactoryBean;

//泛型内容<>内填写返回的类型
public class JavaBeanFactory implements FactoryBean<JavaBean> {
//    如果子例对象需要DI(依赖注入)则需要进行桥梁连接

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

    public void setAge(int age) {
        this.age = age;
    }
    //    覆写如何实现实例化子类过程
    @Override
    public JavaBean getObject() throws Exception {
        JavaBean javaBean = new JavaBean();
        javaBean.setAge(age);
        javaBean.setName(name);
        return javaBean;
    }
// 设置返回的类全定符
    @Override
    public Class<?> getObjectType() {
        return JavaBean.class;
    }
}

3.Configuration 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="javaBeanFactory" class="com.alphamilk.Ioc6.JavaBeanFactory">
<!--    由于是setter注入,所以用对应的注入方法-->
    <property name="name" value="黄飞宏"/>
    <property name="age" value="99"/>
</bean>
</beans>

4. Test the code

package com.alphamilk.Ioc;

import com.alphamilk.Ioc5.JavaBeanScope;
import com.alphamilk.Ioc6.JavaBean;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class newTest {
    @Test
    public void test(){
//  创建Ioc容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springioc-6.xml");
//        获取组件Bean
        JavaBean bean = (JavaBean) context.getBean("javaBeanFactory");
//        调用Bean方法测试是否有效
        bean.PrintInfo();
    }
}

To summarize the usage scenarios of FactoryBean:

  1. Creation of proxy class
  2. Third-party framework integration
  3. Complex object instantiation, etc.

Easy to confuse - the difference between interview questions FactoryBean and BeanFactory

  1. **FactoryBean ** is a special bean in Spring. Beans can be created with custom logic in the getObject() factory method! Is a Bean that can produce other Beans. FactoryBean is created when the container starts, and when actually used, the beans it produces are obtained by calling the getObject() method. Therefore, FactoryBean can customize any required initialization logic and produce some customized beans.
  2. Under normal circumstances, integrating third-party frameworks is achieved by defining FactoryBean! ! !
  3. BeanFactory is the foundation of the Spring framework. As a top-level interface, it defines the basic behavior of the container, such as managing the life cycle of beans, loading and parsing configuration files, bean assembly and dependency injection, etc. The BeanFactory interface provides ways to access beans, such as the getBean() method to obtain a specified bean instance. It can obtain bean definitions from different sources (such as Mysql database, XML files, Java configuration classes, etc.) and convert them into bean instances. At the same time, BeanFactory also contains many subclasses (for example, ApplicationContext interface) that provide additional powerful functions.
  4. In general, the main difference between FactoryBean and BeanFactory is that the former is an interface for creating beans, which provides more flexible initialization customization functions, while the latter is a framework basic interface for managing beans, providing basic container functions and Bean life cycle management.

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132478622