Instantiation of spring beans
1. Constructor instantiation
<! -- no argument constructor instantiation --> <bean id="student1" class="com.qfedu.entity.Student">
<property name="id" value="100"></property>
<property name="name" value="xiaoming"></property>
</bean>
Copy the code
2. 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
/** * static factory * static method to create objects */
public class StaticFactory {
/** * Static method creates object *@return* /
public static Student createStudent(a){
Student student = new Student();
// The benefit is that the programmer can customize the initialization object and hand it over to the Spring container to create
student.setId(123);
student.setName("Xiao Ming");
returnstudent; }}Copy the code
<! Tell the container to use static factories to create objectsclass="com.qfedu.factory.StaticFactory"Static factory factory-method="createStudent"The method name that calls the static factory --> <bean id="student2" class="com.qfedu.factory.StaticFactory" factory-method="createStudent">
</bean>
Copy the code
3. Instance factory instantiation
/** * Instance factory creates object */
public class Factory {
/** * The instance method creates object *@return* /
public Student createStudent(a){
Student student = new Student();
// The benefit is that the programmer can customize the initialization object and hand it over to the Spring container to create
student.setId(123);
student.setName("Xiao Ming");
returnstudent; }}Copy the code
<? 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 instance factory --> <bean id="factory" class="com.qfedu.factory.Factory"> </bean> <! -- Create student using factory factory-bean="factory"Reference the instance factory factory-method="createStudent"Call the instance method in the instance factory --> <bean id="student" factory-bean="factory" factory-method="createStudent">
</bean>
</beans>
Copy the code
4. 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
1. Singleton mode
<! Let the container create a student that defaults to singleton scope="singleton"The singleton creates the bean at startup regardless of whether the user gets the bean or not, and creates only one corresponding 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>
Copy the code
2. Prototype testing
<! Tell the container to create a prototype bean id="student1"When is it created? The container is only responsible for creating, not holding, and managing the bean --> <bean ID ="student1" class="com.qfedu.entity.Student" scope="prototype">
<property name="id" value="100"></property>
<property name="name" value="xiaoming"></property>
</bean>
Copy the code
3. The test
public class ScopeTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scope/scope_bean.xml");
System.out.println("Singleton test");
// The bena of a singleton is a singleton no matter how many times it is fetched
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 testing");
// Get a new object each time. The container is only responsible for creating, not maintaining, the prototype bean
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: Handed over to the container for maintenance, the container manages beans
The life cycle of a bean is scoped by the bean
1.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 and manages beans
The singleton bean is created and held when the container is initialized, and destroyed when the container is destroyed
2.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 initializes, it does not create beans. It only creates beans when it fetches them. Spring creates beans, does not hold them, and does not destroy them
public class Student implements Serializable {
private int id;
private String name;
/** * Initializes resources */
public void init(a){
System.out.println("Student initialization method");
}
/** * Release resources */
public void destroy(a){
System.out.println("Student Destruction Method"); }... }Copy the code
<? 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"> <! -- singleton bean scope="singleton"
init-method="init"The bean calls the initialization method destroy-method= when it is created"destroy"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> <! -- Prototype bean scope="prototype"
init-method="init"The bean calls the initialization method destroy-method= when it is created"destroy"Container destruction method --> <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="Zhang"></property>
</bean>
</beans>
Copy the code
Testing:
/** * Bena life cycle */
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, which calls the destroy() method on all beans in the container
// The singleton bean calls destroy()
// The prototype bean does not call destroy() because the container does not hold the beanclassPathXmlApplicationContext.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
1. Xml-based assembly
Property and constructor set values (with and without arguments)
<? 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"> <! Initialize the bean with setter via no-argument construction --> <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> <! -- Created by a parameter constructbean
public Student(int id, String name, String sex, List<String> course)
0 1 2 3
<constructor-arg index="0" value="111"></constructor-arg> Sets the 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
2. The 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, a token, that creates beans through annotations and manages dependencies between beans
Injected annotations. Attributes in an instance can be retrieved from the container using the following annotations and injected into the bean:
@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.
1.@Autowired + @Qualifier
Comments to enable injection:
<! -- This is a switch, activate@Autowired@resource, @postconstruct, @predestroy let them work --> <context:annotation-config></context:annotation-config>Copy the code
Add annotations to the container:
<! StudentDaoImpl --> <bean id="studentDao1" class="com.qfedu.dao.StudentDaoImpl"></bean>
<bean id="studentDao2" class="com.qfedu.dao.StudentDaoImpl"></bean> <! Add StudentServiceImpl to 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. If you cannot find it by variable name, you can use the @Qualifier("studentDao2") configuration to look for */ as the iD of the passed parameter
// Go to the container to find the StudentDao instance and reference the current attribute
@Autowired
@Qualifier("studentDao2")Use @qualifier if more than one is found
private StudentDao studentDao;
// public void setStudentDao(StudentDao studentDao){
// this.studentDao = studentDao;
/ /}
public Student findStudentById(int id) {
returnstudentDao.findStudentById(id); }}Copy the code
2.@Resource
Comments to enable injection:
<! -- This is a switch, activate@Autowired@resource, @postconstruct, @predestroy let them work --> <context:annotation-config></context:annotation-config>Copy the code
Add annotations to the container:
<! StudentDaoImpl --> <bean id="studentDao1" class="com.qfedu.dao.StudentDaoImpl"></bean>
<bean id="studentDao2" class="com.qfedu.dao.StudentDaoImpl"></bean> <! Add StudentServiceImpl to the container --> <bean id="studentService" class="com.qfedu.service.StudentServiceImpl"></bean>
Copy the code
Assembly:
public class StudentServiceImpl implements StudentService{
/* * @resource also injects the 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. Meaning * 3.@Resource is a JDK annotation @autowired is a Spring annotation * */
@Resource(name = "studentDao2")
private StudentDao studentDao;
// public void setStudentDao(StudentDao studentDao){
// this.studentDao = studentDao;
/ /}
public Student findStudentById(int id) {
returnstudentDao.findStudentById(id); }}Copy the code
conclusion
1.@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
2.@Resource also injects beans from the container into the current object
1. Use the declared attribute name as the ID 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
3.@Autowired @Resource difference?
1.@Resource(name = “studentDao2”) is equivalent to @autowired @qualifier
2.@Resource is the JDK annotation @autowired Spring annotation
Generate annotations for the bean
@Component//@Component // Add the bean to the container with the default ID studentServiceImpl
@Component(” studentService “) // Add the bean ID to the container. StudentService Is a child annotation of @Component
@service used for service@Controller 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"> <! Package scanner: Enable injection annotations@AutowiredThe @resource enables the annotation of the generated bean@Component
//@Component // Add the bean's default id studentServiceImpl to the container
@Component("studentService") // Add the bean ID studentService to the containerThe following three usages and@ComponentThe same is@ComponentA child of the annotation@ServiceFor the service@ControllerFor control layer@RepositoryFor the persistence layer DAO --> <context:component-scan base-package="com.qfedu"></context:component-scan>
</beans>
Copy the code
//@Component // Add the bean's default id studentServiceImpl to the container
//@Component("studentService") // Add the bean ID studentService to the container
@Service("studentService")// Add it to container ID studentService
public class StudentServiceImpl implements StudentService {
// Go to the container to find the StudentDao instance and reference the current attribute
/ * * *@AutowiredSetsetmethods are not required to support * meaning: 1. First look in the container according to the annotation type if 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 cannot be found by variable name, use@Qualifier("studentDao2") configuration to look for * * as iD with the passed argument@ResourceAlso inject the 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. If not found by type search, if found a setting value if multiple, enter the third part * 3.@Resource(name = "studentDao2") If you find more than one type of bean you must pass name as id to qualify * *@Autowired @ResourceThe difference between? * * 1.@Resource(name = "studentDao2") equivalent to@Autowired @Qualifier* 2. Meaning * 3.@ResourceThe JDK annotations@AutowiredThe spring annotation * */
// @Autowired
@qualifier ("studentDao2")// Use @qualifier if more than one is found
@Resource
private StudentDao studentDao ;
// public void setStudentDao(StudentDao studentDao) {
// this.studentDao = studentDao;
/ /}
public Student findStudentById(int id) {
returnstudentDao.findStudentById(id); }}Copy the code
//@Component// Add a bean to the container id studentDaoImpl
@Repository // Add to container id studentDaoImpl
public class StudentDaoImpl implements StudentDao{
public Student findStudentById(int id) {
// simulate a database query
Student student = new Student();
student.setId(id);
student.setName("XXXXX");
returnstudent; }}Copy the code
Testing:
/** * automatic transfer */
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
<? 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= add it to the container"byName"Properties in the container look up autowire= in the container based on the property name as id"byType"Properties in the container look up autowire= in the container based on the property type"constructor"Set the property according to the constructor --> <bean id="studentService" class="com.qfedu.service.StudentServiceImpl" autowire="byName">
</bean>
</beans>
Copy the code
conclusion
Thank you for watching, come to all might as well click a “like” and then go!
Microservices +MySQL+ distributed +SSM framework +Java+Redis+ data structure and algorithm + network +Linux+Spring family bucket +JVM+ high concurrency + major learning thinking brain map + interview set docs.qq.com/doc/DS0doWl…