1

Instantiation of spring bean

Constructor instantiation

 <!--
        无参构造器实例化
    -->
    <bean id="student1" class="com.qfedu.entity.Student">
        <property name="id" value="100"></property>
        <property name="name" value="xiaoming"></property>
    </bean>

Static factory instantiation

The container creates the object, instead of directly calling the object construction method, but calling the method of creating the object of the static factory
Benefits: It is convenient for us to customize the creation of objects, the initialization of objects, and the need to access data in the network

/**
 * 静态工厂
 *    静态方法创建对象
 */
public class StaticFactory {


    /**
     * 静态方法 创建对象
     * @return
     */
    public static Student createStudent(){

        Student student = new Student();

        
        // 好处就是 程序员可以 自定义 初始化对象,并交给spring容器创建 
        student.setId(123);
        student.setName("小明");

        return  student;
    }

}
<!--
       告诉容器使用静态工厂 创建对象
        class="com.qfedu.factory.StaticFactory" 静态工厂
        factory-method="createStudent" 调用静态工厂的方法名
    -->
    <bean id="student2" class="com.qfedu.factory.StaticFactory" factory-method="createStudent">

    </bean>

individuals have sorted out some information, and friends in need can click to get them directly.

Java basic knowledge

22 core Java architect books

Java learning routes and materials from 0 to 1

1000+ 2021 latest

Instance factory instantiation

/**
 * 实例工厂 创建对象
 */
public class Factory {


    /**
     * 实例方法 创建对象
     * @return
     */
    public  Student createStudent(){

        Student student = new Student();


        // 好处就是 程序员可以 自定义 初始化对象,并交给spring容器创建
        student.setId(123);
        student.setName("小明");

        return  student;
    }
}
<?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="factory" class="com.qfedu.factory.Factory">

    </bean>
    <!--
            目标创建 student  使用实例工厂
                factory-bean="factory" 引用实例工厂
                factory-method="createStudent" 调用实例工厂中的实例 方法
    -->
    <bean id="student" factory-bean="factory" factory-method="createStudent">

    </bean>

</beans>

Use scenarios for factory instantiation

The role of factory instantiation: easy for programmers to create custom objects
Usage scenario: When initializing database data, decrypt the database password, and place the data source in the container to improve security

bean scope

Scope: the scope of the bean's survival in the container
Commonly used: singleton, prototype

Singleton mode

<!--
       让容器创建一个student
       默认 该bean 作用域 是单例singleton  scope="singleton"
             单例singleton 无论用户是否获取该bean,容器在启动创建该bean,而且只创建一个 对应bean id为 student
   -->
   <bean id="student" class="com.qfedu.entity.Student" scope="singleton">
       <property name="id" value="100"></property>
       <property name="name" value="xiaoming"></property>
   </bean>

Prototype test


    <!--
        告诉容器创建一个 原型 bean  id="student1"
        什么时候创建? 容器启动不创将该bean,在用户获取时创建,而且每获取一次创建一个bean,容器只负责创建,
        不负责持有,管理该bean
    -->
    <bean id="student1" class="com.qfedu.entity.Student" scope="prototype">
        <property name="id" value="100"></property>
        <property name="name" value="xiaoming"></property>
    </bean>

test

public class ScopeTest {
    public static void main(String[] args) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scope/scope_bean.xml");

        System.out.println("单例测试");
        //单例的bena无论获取多少次都是单例
        Student student1 = (Student) applicationContext.getBean("student");

        Student student2 = (Student) applicationContext.getBean("student");

        System.out.println("student1 == student2:" + (student1 == student2));

        System.out.println("*********");
        System.out.println("原型测试");
        // 获取 原型bean, 每次获取都是一个新的对象,容器只负责创建,不负责持有,维护
        Student student3 = (Student) applicationContext.getBean("student1");

        Student student4 = (Student) applicationContext.getBean("student1");

        System.out.println("student3 == student4:" + (student3 == student4));
    }
}

bean life cycle

bean: hand over to the container for maintenance, container-managed beans
The scope of the bean life cycle is related to the scope of the bean

singleton

The Spring container can manage the life cycle of a bean in the singleton scope. In this scope, Spring can accurately know when the bean is created, when it is initialized, and when it is destroyed.

The container creates beans and manages beans
Create a singleton bean when the container is initialized, and hold the bean, and destroy the bean when the container is destroyed

prototype

Spring is only responsible for creating the Bean in the prototype scope. When the container creates a Bean instance, the Bean instance is handed over to the client code for management, and the Spring container will no longer track its life cycle.

The container only creates beans without management
When the container is initialized, the bean will not be created, and the bean will be created only when it is acquired. Spring is only responsible for creating, not holding the bean, and not responsible for destroying it. You can also configure the init() initialization method and destroy() method for the bean.

public class Student implements Serializable {

    private int id;

    private String name;

    /**
     * 初始化 资源
     */
    public void  init(){

        System.out.println("Student 初始化方法");
    }

    /**
     * 释放资源
     */
    public void destroy(){
        System.out.println("Student 销毁方法");
    }
。。。。
}
<?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 scope="singleton"

              init-method="init" bean 在创建时调用 初始化方法
              destroy-method="destroy" 容器销毁 方法
    -->

    <bean id="student1" class="com.qfedu.entity.Student" scope="singleton"
          init-method="init" destroy-method="destroy">
        <property name="id" value="100"></property>
        <property name="name" value="xiaoming"></property>
    </bean>



    <!--
    原型bean scope="prototype"

          init-method="init" bean 在创建时调用 初始化方法
          destroy-method="destroy" 容器销毁 方法
-->
    <bean id="student2" class="com.qfedu.entity.Student" scope="prototype"
          init-method="init" destroy-method="destroy">
        <property name="id" value="100"></property>
        <property name="name" value="张三"></property>
    </bean>
</beans>

test:

/**
 *bena的生命周期
 */
public class LifeTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext  = new ClassPathXmlApplicationContext("life/life_bean.xml");

        Student student1 = (Student) classPathXmlApplicationContext.getBean("student1");

        System.out.println(student1);
        System.out.println("容器销毁");

        // 明示销毁容器,此时会调用容器中所有bean destroy() 方法
        // 单例bean 调用 destroy()
        // 原型bean  不会调用 destroy()  因为容器不持有该bean
        classPathXmlApplicationContext.destroy();
    }
}

Bean assembly

What Bean assembly?
Is the setting of bean properties and the configuration of dependencies between beans

XML-based assembly

Property and construction method setting value (no parameter and parameter)

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


    <!--
         通过无参构造 使用setter 初始化bean
    -->
    <bean id="student1" class="com.qfedu.entity.Student">
        <property name="id" value="100"></property>
        <property name="name" value="xiaoming"></property>
        <property name="sex" value="F"></property>

        <property name="course" >

            <list>
                <value>Java</value>
                <value>UI</value>
                <value>H5</value>
                <value>php</value>
            </list>
        </property>
    </bean>

    <!--
        通过有参构造创建  bean
        public Student(int id, String name, String sex, List<String> course)
                            0        1               2          3
                            
          <constructor-arg index="0" value="111"></constructor-arg> 为每一个构造方法的参数设置
          属性                     
     -->
    <bean id="student1" class="com.qfedu.entity.Student">

        <constructor-arg index="0" value="111"></constructor-arg>
        <constructor-arg index="1" value="zhangsan"></constructor-arg>
        <constructor-arg index="2" value="F"></constructor-arg>
        <constructor-arg index="3" >
            
            <list>
                <value>Java</value>
                <value>UI</value>
                <value>H5</value>
                <value>php</value>
            </list>
        </constructor-arg>
    </bean>

</beans>

test

public class XmlTest {
    public static void main(String[] args) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("xml/xml_bean.xml");

        Student student1 = (Student) applicationContext.getBean("student1");
        System.out.println("student1 = " + student1);

        Student student2 = (Student) applicationContext.getBean("student2");
        System.out.println("student2 = " + student2);
    }
}

Annotation-based assembly

Note: is a mark, mark
Create beans through annotations and manage dependencies between beans

Injected annotations
The attributes in an instance can be obtained from the container and injected into the corresponding bean through the following annotations:

@Autowired: Used to annotate the attribute variables, attribute setter methods and construction methods of the Bean, and cooperate with the corresponding annotation processor to complete the automatic configuration of the Bean

@Qualifier: Used in conjunction with the @Autowired annotation, the default assembly by Bean type will be modified to assembly by the instance name of the Bean. The instance name of the Bean is specified by the parameter of the @Qualifier annotation.

@Resource: Its role is the same as Autowired. There are two important attributes in @Resource: name and type. Spring resolves the name attribute to the Bean instance name, and the type attribute resolves to the Bean instance type.

@Autowired + @Qualifier

Activate the injected annotation:

 <!--

        这是一个开关,激活 @Autowired    @ Resource 、@ PostConstruct、@ PreDestroy
                       让他们生效
    -->
    <context:annotation-config></context:annotation-config>

Add comments to the container:

<!--
       将StudentDaoImpl加入到容器中StudentDaoImpl
   -->
    <bean id="studentDao1" class="com.qfedu.dao.StudentDaoImpl"></bean>
    <bean id="studentDao2" class="com.qfedu.dao.StudentDaoImpl"></bean>

    <!--
       将StudentServiceImpl加入到容器中
   -->
    <bean id="studentService" class="com.qfedu.service.StudentServiceImpl"></bean>

assembly:

public class StudentServiceImpl implements StudentService{


    /*@Autowired 不需要 setter方法支持
     * 意义: 1.首先根据注解的类型 去容器中查找 如果只有一个,则设置
     *       2.如果按照类型查找到 多个 ,则使用 变量名( private StudentDao studentDao) 作为id 去容器中查找
     *       3.如果按照变量名找不到,可以使用@Qualifier("studentDao2") 配置,按照传递的参数作为iD 查找
     */

    // 去容器中查找 StudentDao 对应实例,并将当前 属性引用
    @Autowired
    @Qualifier("studentDao2")//如果找到多个使用  @Qualifier区分
    private StudentDao studentDao;

//    public void setStudentDao(StudentDao studentDao){
//        this.studentDao = studentDao;
//    }

    public Student findStudentById(int id) {
        return studentDao.findStudentById(id);
    }
}

@Resource

Activate the injected annotation:

 <!--

        这是一个开关,激活 @Autowired    @ Resource 、@ PostConstruct、@ PreDestroy
                       让他们生效
    -->
    <context:annotation-config></context:annotation-config>

Add comments to the container:


    <!--
       将StudentDaoImpl加入到容器中StudentDaoImpl
   -->
    <bean id="studentDao1" class="com.qfedu.dao.StudentDaoImpl"></bean>
    <bean id="studentDao2" class="com.qfedu.dao.StudentDaoImpl"></bean>

    <!--
       将StudentServiceImpl加入到容器中
   -->
    <bean id="studentService" class="com.qfedu.service.StudentServiceImpl"></bean>

assembly:

public class StudentServiceImpl implements StudentService{


    /*
     *  @Resource  也是 将容器中的bean 注入到当前对象中
     * 意义:
     *      1.首先按照声明 属性名作为id 去容器中查找(private StudentDao studentDao ),
     *      2.如果没有找到 按照类型查找 ,如果查找到一个则设置值, 如果查到多个,则进入第三步
     *      3.@Resource(name = "studentDao2"): 如果找到多个类型的bean 必须传入name 作为id 进行限定
     *
     * @Autowired    @Resource 的区别?
     *
     * 1. @Resource(name = "studentDao2") 等价于 @Autowired  @Qualifier
     * 2.意义
     * 3.@Resource 是jdk 注解 @Autowired 是spring 注解
    * */

    @Resource(name = "studentDao2")
    private StudentDao studentDao;

//    public void setStudentDao(StudentDao studentDao){
//        this.studentDao = studentDao;
//    }

    public Student findStudentById(int id) {
        return studentDao.findStudentById(id);
    }
}

to sum up

@Autowired does not require setter method support

  • Significance: 1. First find in the container according to the type of annotation, if there is only one, then set
  • 2. If you find more than one by type, use the variable name (private StudentDao studentDao) as the id to search in the container
  • 3. If you can’t find it according to the variable name, you can use @Qualifier(“studentDao2”) to configure and look up the passed parameter as iD

*

  • @Resource also injects the beans in the container into the current object
  • significance:
  • 1. First follow the declared attribute name as id to find in the container (private StudentDao studentDao),
  • 2. If not found, search by type, if you find a setting value, if there are multiple, then enter the third part
  • 3.@Resource(name = "studentDao2") If multiple types of beans are found, name must be passed in as the id for qualification

*

  • The difference between @Autowired @Resource?

*

    1. @Resource(name = “studentDao2”) is equivalent to @Autowired @Qualifier
  • 2. Meaning
  • 3.@Resource is jdk annotation @Autowired spring annotation

*

Generate bean annotations

@Component
//@Component // Add bean default id studentServiceImpl to the container
@Component("studentService") // add bean id studentService to the container
The following three usages are the same as @Component sub-annotations of @Component
@Service for service
@Controller is used for the control layer
@Repository is used for the persistence layer dao

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">


    <!--
        包扫描器 :
        激活 注入注解   @Autowired    @ Resource
        激活生成bean 的注解
            @Component
                    //@Component // 在容器中加入bean 默认id  studentServiceImpl
                    @Component("studentService")   // 在容器中加入bean id  studentService
            以下三个用法和 @Component 一样是@Component 的子注解
            @Service   用于service
            @Controller 用于控制层
            @Repository  用于持久层 dao
    -->
    <context:component-scan base-package="com.qfedu"></context:component-scan>


</beans>
//@Component // 在容器中加入bean 默认id  studentServiceImpl
//@Component("studentService")   // 在容器中加入bean id  studentService
@Service("studentService")// 加入到容器  id  studentService
public class StudentServiceImpl implements StudentService {

    // 去容器中查找 StudentDao 对应实例,并将当前 属性引用
    /**
     *  @Autowired 不需要 setter方法支持
     * 意义: 1.首先根据注解的类型 去容器中查找 如果只有一个,则设置
     *       2.如果按照类型查找到 多个 ,则使用 变量名( private StudentDao studentDao) 作为id 去容器中查找
     *       3.如果按照变量 名找不到,可以使用@Qualifier("studentDao2") 配置,按照传递的参数作为iD 查找
     *
     * @Resource  也是 将容器中的bean 注入到当前对象中
     * 意义:
     *      1.首先按照声明 属性名作为id 去容器中查找(private StudentDao studentDao ),
     *      2.如果没有找到 按照类型查找 ,如果查找到一个设置值 如果多个,则进入第三部
     *      3.@Resource(name = "studentDao2") 如果找到多个类型的bean 必须传入name 作为id 进行限定
     *
     * @Autowired    @Resource 的区别?
     *
     * 1. @Resource(name = "studentDao2") 等价于 @Autowired  @Qualifier
     * 2.意义
     * 3.@Resource 是jdk 注解 @Autowired spring 注解
     *
     */
//    @Autowired
//    @Qualifier("studentDao2")//如果找到多个使用  @Qualifier区分
    @Resource
    private StudentDao studentDao ;

//    public void setStudentDao(StudentDao studentDao) {
//        this.studentDao = studentDao;
//    }

    public Student findStudentById(int id) {
        return studentDao.findStudentById(id);
    }
}
//@Component// 将当前类 创建一个bean 加入到容器中 id studentDaoImpl
@Repository // 加入到容器 id studentDaoImpl
public class StudentDaoImpl implements StudentDao{
    public Student findStudentById(int id) {

        // 模拟取数据库查询
        Student student = new Student();
        student.setId(id);
        student.setName("XXXXX");

        return student;
    }
}

test:

/**
 * 自动转配
 */
public class AnnootaionTest {


    public static void main(String[] args) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("annotation/auto_annotation.xml");


        StudentService studentService = (StudentService) applicationContext.getBean("studentService");


        Student student =  studentService.findStudentById(12);
        System.out.println("student"+student);
    }

}

Automatic assembly based on 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="studentDao1" class="com.qfedu.dao.StudentDaoImpl"></bean>
    <bean id="studentDao" class="com.qfedu.dao.StudentDaoImpl"></bean>

    <!--
        加入到容器中  StudentServiceImpl

         autowire="byName" 容器中的属性 会根据属性名作为id 去容器中查找
         autowire="byType"  容器中的属性 会根据属性类型   去容器中查找
          autowire="constructor" 根据构造方法设置 属性 
    -->
    <bean id="studentService" class="com.qfedu.service.StudentServiceImpl" autowire="byName">

    </bean>

</beans>

At last

Thanks to the big guys for seeing this, you might as well click a thumbs up before you leave.


前程有光
936 声望618 粉丝