Instantiation of spring beans

Constructor instantiation

<! Class ="com.qfedu.entity.Student"> <property name="id" value="100"></property> <property name="name" value="xiaoming"></property> </bean>Copy the code

Static factory instantiation

The container does not call the object constructor directly, but calls the static factory object creation method. The advantage is that we can customize the object creation, and the object initialization needs to access the data in the network

Public class StaticFactory {/** ** @return */ public static Student createStudent(){ Student student = new Student(); // The benefit is that programmers can customize the initialization object and hand it to the Spring container to create student.setid (123); Student. Elegantly-named setName (" Ming "); return student; }}Copy the code
<! - tell the container to use static factories create the object class = "com. Qfedu. Factory. StaticFactory" static factory factory - method = "createStudent calls" static factory method name - > < bean id="student2" class="com.qfedu.factory.StaticFactory" factory-method="createStudent"> </bean>Copy the code

I sorted out some information, and friends in need can click to get it directly.

Java Basics

22 Java Architect Core books

Learning routes and materials from 0 to 1Java

1000+ questions from 2021

Instance factory instantiation

/** * public class Factory create object */ ** * public class Factory create object * @return */ public Student createStudent(){Student Student =  new Student(); // The benefit is that programmers can customize the initialization object and hand it to the Spring container to create student.setid (123); Student. Elegantly-named setName (" Ming "); return student; }}Copy the code
<? The 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"> <! - create an instance factory - > < bean id = "factory" class = "com. Qfedu. Factory. Factory" > < / bean > <! <bean id="student" <bean id="student" <bean id="student"  factory-bean="factory" factory-method="createStudent"> </bean> </beans>Copy the code

Usage scenarios for factory instantiation

The factory instantiation function is convenient for programmers to create customized objects. Usage scenario: When initializing database data, decrypt the database password and place the data source in a container to improve security

The scope of the bean

Scope: the scope in which the bean lives in the container is commonly used: singleton, stereotype

The singleton pattern

<! Singleton scope="singleton" Singleton scope="singleton" Singleton scope="singleton" singleton scope="singleton" singleton scope="singleton student --> <bean id="student" class="com.qfedu.entity.Student" scope="singleton"> <property name="id" value="100"></property> <property name="name" value="xiaoming"></property> </bean>Copy the code

The prototype test

<! Tell the container to create a prototype bean id="student1" when to create? Container startup does not create the bean, it is created when the user obtains the bean, and each time the bean is created, the container is only responsible for creating, not holding, the bean. Class ="com.qfedu.entity.Student" scope="prototype"> value="100"></property> <property name="name" value="xiaoming"></property> </bean>Copy the code

test

public class ScopeTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scope/scope_bean.xml"); System.out.println(" singleton test "); / / the singleton bena no matter how many times is a singleton for 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(" prototype test "); / / get the prototype bean, access is a new object each time, the container is only responsible for creating, not responsible for hold, maintain Student student3 = (Student) applicationContext. GetBean (" student1 "); Student student4 = (Student) applicationContext.getBean("student1"); System.out.println("student3 == student4: "+ (student3 == student4)); }}Copy the code

The life cycle of the bean

Beans: Given to the container for maintenance, container-managed beans are scoped for the bean’s life cycle

singleton

The Spring container can manage the life cycle of singleton-scoped beans, where Spring knows exactly when the Bean was created, initialized, and destroyed.

The container creates beans, manages beans, creates singleton beans when the container is initialized, and holds beans, and destroys beans when the container is destroyed

prototype

The prototype-scoped Bean is only created by Spring. When the container creates a Bean instance, the Bean instance is managed by the client code and the Spring container no longer tracks its lifecycle.

When the container is initialized, it does not create beans. It only creates beans when it fetches them. Spring only creates beans, it does not hold them, and it does not destroy them

public class Student implements Serializable { private int id; private String name; Public void init(){system.out.println ("Student init method "); / / Public void init(){system.out.println ("Student init method "); } public void destroy(){system.out.println ("Student destroy method "); }... }Copy the code
<? The 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"> <! Scope ="singleton" init-method="init" the bean calls the initialization method destroy-method="destroy" the container destruction method --> <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> <! Scope ="prototype" init-method="init"; scope="prototype" init-method=" destroy"; scope="prototype" init-method=" destroy"; scope="prototype" init-method=" destroy" id="student2" class="com.qfedu.entity.Student" scope="prototype" init-method="init" destroy-method="destroy"> <property </property> <property name="name" value="100"></property> </property> </beans>Copy the code

Testing:

/ * * * the life cycle of 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(" container destruction "); // Explicitly destroy the container, All bean destroy() methods in the container are called. // The singleton bean calls destroy(). // The prototype bean does not call destroy() because the container does not hold the bean classPathXmlApplicationContext.destroy(); }}Copy the code

The assembly of the Bean

Assembly of what beans? This is the setting of bean properties and the configuration of dependencies between beans

Xml-based assembly

Property and constructor set values (with and without arguments)

<? The 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="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> <! Public Student(int id, String name, String sex, List<String> course) 0 1 2 3 <constructor-arg index="0" value="111"></constructor-arg> Set attribute for each constructor parameter --> <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>Copy the code

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); }}Copy the code

Annotation-based assembly

Annotations: Is a tag that creates beans through annotations and manages dependencies between beans

Injected annotations Properties in an instance can be injected with the following annotations to get the corresponding bean from the container:

@autowired: it is used to annotate the Bean’s attribute variables, setter methods and constructors, 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 is changed to assembly by the instance name of the Bean, which is specified by the @qualifier annotation parameter.

@Resource: Does the same thing 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 to the Bean instance type.

@Autowired + @Qualifier

Comments to enable injection:

<! -- This is a switch. Activate @autoWired @Resource, @postConstruct, @predestroy and let them work --> <context:annotation-config></context:annotation-config>Copy the code

Add annotations to the container:

<! - will StudentDaoImpl added to the container StudentDaoImpl - > < bean id = "studentDao1" class = "com. Qfedu. Dao. StudentDaoImpl" > < / bean > < bean id="studentDao2" class="com.qfedu.dao.StudentDaoImpl"></bean> <! - adding StudentServiceImpl into the container - > < bean id = "studentService" class = "com. Qfedu. Service. StudentServiceImpl" > < / bean >Copy the code

Assembly:

Public class StudentServiceImpl implements StudentService{/* @autoWired Does not require setter support * Meaning: 1 First look in the container for the annotation type if there is only one, set * 2. If multiple ids are found by type, use the variable name (private StudentDao StudentDao) as the ID to search for * 3 in the container. Note If the variable name is not available, use @Qualifier("studentDao2") to find the iD */ // in the container to find the instance of StudentDao. @autoWired @Qualifier("studentDao2")// If there are more than one @qualifier to separate private StudentDao from StudentDao; // public void setStudentDao(StudentDao studentDao){ // this.studentDao = studentDao; // } public Student findStudentById(int id) { return studentDao.findStudentById(id); }}Copy the code

@Resource

Comments to enable injection:

<! -- This is a switch. Activate @autoWired @Resource, @postConstruct, @predestroy and let them work --> <context:annotation-config></context:annotation-config>Copy the code

Add annotations to the container:

<! - will StudentDaoImpl added to the container StudentDaoImpl - > < bean id = "studentDao1" class = "com. Qfedu. Dao. StudentDaoImpl" > < / bean > < bean id="studentDao2" class="com.qfedu.dao.StudentDaoImpl"></bean> <! - adding StudentServiceImpl into the container - > < bean id = "studentService" class = "com. Qfedu. Service. StudentServiceImpl" > < / bean >Copy the code

Assembly:

Public class StudentServiceImpl implements StudentService{/* * @resource Implements a bean from the container into the current object. First, use the declared attribute name as the ID to search in the container (private StudentDao StudentDao). * 2. * 3.@Resource(name = "studentDao2"): If more than one type of bean is found, name must be passed as id to qualify the difference between * * @autowired @resource? @resource (name = "studentDao2") is equivalent to @autowired @qualifier * 2. * */ @resource (name = "studentDao2") private StudentDao StudentDao; // public void setStudentDao(StudentDao studentDao){ // this.studentDao = studentDao; // } public Student findStudentById(int id) { return studentDao.findStudentById(id); }}Copy the code

conclusion

@autoWired does not require setter method support

  • Meaning: 1. First look in the container according to the annotation type if only one, then set
  • 2. If multiple ids are found based on the type, use the variable name (private StudentDao StudentDao) as the ID to search for the ids in the container
  • 3. If you cannot find it according to the variable name, use @Qualifier(” studentDao2 “) to find the iD based on the passed parameter
  • @Resource also injects beans from the container into the current object
  • Meaning:
  • 1. Use the declared attribute name as the ID to search for it in the container (private StudentDao StudentDao).
  • 2. If no value is found, search by type. If multiple values are found, go to the third step
  • 3.@Resource(name = “studentDao2”) If you find more than one type of bean you must pass in name as id to qualify it
  • What’s the difference between @autowired @Resource?
    1. @resource (name = “studentDao2”) is equivalent to @autowired @qualifier
  • Meaning of 2.
  • 3.@Resource is the JDK annotation @autowired Spring annotation

Generate annotations for the bean

@Component //@Component // Add the bean to the container Default ID studentServiceImpl @Component(” studentService “) // Add the bean ID to the container StudentService is a child annotation of @Component. @Service is for Service. @Controller is for the control layer. @Repository is for the persistence layer dao

<? The 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"> <! -- Packet scanner: @Component //@Component // Add the bean default ID studentServiceImpl to the container @Component("studentService") // Add the bean ID to the container. StudentService is a child annotation of @Component Dao --> <context:component-scan base-package="com.qfedu"></context:component-scan> </beans>Copy the code
//@Component // Add the bean to the container studentServiceImpl //@Component("studentService") // Add the bean ID to the container studentService @service ("studentService")// Adds to the container ID studentService Public class StudentServiceImpl implements studentService {// /** * @autoWired does not need setter support * meaning: 1 First look in the container for the annotation type if there is only one, set * 2. If multiple ids are found by type, use the variable name (private StudentDao StudentDao) as the ID to search for * 3 in the container. If it is not found by variable name, you can configure it using @Qualifier("studentDao2") to look for the passed parameter as iD. * * @resource is also used to inject beans from the container into the current object. First, use the declared attribute name as the ID to search in the container (private StudentDao StudentDao). * 2. If you don't find it look by type, if you find one setting if you have more than one, 3.@Resource(name = "studentDao2") if you find more than one type of bean, you must pass in name as id to qualify it. @resource (name = "studentDao2") is equivalent to @autowired @qualifier * 2. Meaning * 3.@Resource is the JDK annotation @autowired spring annotation * */ / @autowired // @qualifier ("studentDao2")// Use @qualifier if multiple are found @Resource private StudentDao studentDao ; // public void setStudentDao(StudentDao studentDao) { // this.studentDao = studentDao; // } public Student findStudentById(int id) { return studentDao.findStudentById(id); }}Copy the code
//@Component// Add a bean to the container id studentDaoImpl @repository // Add a bean to the container ID studentDaoImpl public class studentDaoImpl Implements StudentDao{public Student findStudentById(int ID) {// New Student = new Student(); student.setId(id); student.setName("XXXXX"); return student; }}Copy the code

Testing:

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); }}Copy the code

Automatic assembly based on XML

<? The 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" Autowire ="byType" Autowire ="byType" Autowire ="byType Autowire = "constructor" according to the constructor properties - > < bean id = "studentService" class = "com. Qfedu. Service. StudentServiceImpl" autowire="byName"> </bean> </beans>Copy the code

The last

Well, thank you guys for seeing this, but you might as well give it a thumbs up before you leave