当前位置:网站首页>Bean's life cycle & dependency injection * dependency auto assembly
Bean's life cycle & dependency injection * dependency auto assembly
2022-07-27 05:19:00 【New an object_】
️️️
bean Life cycle
Life cycle : The whole process from creation to extinction
*bean Life cycle :bean( object ) The whole process from creation to destruction
*bean Life cycle control : stay bean Do something after creation and before destruction
️ adopt Bean The configuration of controls its lifecycle
<!-- init-method: Method of initialization destroy-method: Method of destruction -->
<bean id="bookDao" name="bookDao2 bookDao3 " class="com.GY.dao.impl.BookDaoImpl" init-method="M1" destroy-method="M2"/>
package com.GY.dao.impl;
public class BookDaoImpl implements BookDao{
public void save(){
System.out.println("book dao save.......");
}
// Express Bean Initialize the corresponding operation ( Method name is arbitrary )
public void M1(){
/* Write according to business eg: Load some resources or read some files during initialization */
System.out.println(" Before initialization ......");
}
// Express Bean Corresponding operations before destruction ( Method name is arbitrary )
public void M2(){
System.out.println(" Before destruction ......");
}
}
result :
? Why destroy M2 No implementation ?
The program is running in JAVA In the virtual machine , After the virtual machine starts ,IOC Start after loading the configuration ,Bean initialization , Get Bean After the execution , The next action is to exit the virtual machine , Useless give Bean Opportunities for destruction
️️️️
Implement the destroy operation
Mode one :( Close the container manually , Close the container before the virtual machine exits )
This is a more violent way !!!
Mode two :( Register closing hook , Add a mark after the container starts , Close the container before exiting the virtual machine )
These two methods do not need to be written in actual development ( More disorderly ),Spring Through the interface
package com.GY.service.impl;
import com.GY.dao.impl.BookDao;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
private BookDao bookDao;
public void save(){
System.out.println("book service save.....");
bookDao.save();
}
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
// Run after the property value is set
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(3222222);
}
//
@Override
public void destroy() throws Exception {
System.out.println(1111111);
}
}
Bean At the stage of initialization :
● Initialize container
1、 Create objects ( Memory allocation )
2、 Execute construction
3、 Perform property Injection (set operation )
4、 perform bean Initialization method :
● Use bean
1、 Perform business operations
● close / Destruction of the container
1、 perform bean Destruction method
️️️
Dependency injection
There are several ways to pass data to a class ?
* Common method (set Method )
* Construction method
* reflection : Dependency injection describes how to create a in a container bean And bean The process of dependencies between , If bean What you need to run is a number or string ?
● Reference type
● Simple type ( Basic data types and String)
* Dependency injection
●setter Inject ( Simple / Reference type )
◆ stay bean Define reference types and provide accessible set Method
◆ Use... In configuration property label value Property injection simple data type
To configure :
<bean id="bookDao" class="com.GY.dao.impl.BookDaoImpl" >
<property name="count" value="10"/>
<property name="database" value="mysql"/>
</bean>
● Constructor Injection ( Simple / Reference type )******* It is highly coupled with formal parameter names
<!-- Constructor injected name Don't write at will , It is the formal parameter name in the construction method -->
<bean id="bookService" class="com.GY.service.impl.BookServiceImpl" >
<constructor-arg name="bookDao" ref="bookDao"/>
</bean>
<bean id="bookDao" class="com.GY.dao.impl.BookDaoImpl" >
<constructor-arg name="count" value="10"/>
<constructor-arg name="database" value="mysql"/>
</bean>
***************
Solve the problem of parameter type repetition ( Use location to solve ), And solve the formal parameter coupling
<bean id="bookDao" class="com.GY.dao.impl.BookDaoImpl" >
<constructor-arg index="0" value="10"/>
<constructor-arg index="1" value="mysql"/>
<constructor-arg index="2" value="MM"/>
</bean>
public class BookDaoImpl implements BookDao{
private int count;
private String database;
private String MM;
public BookDaoImpl(int count, String database,String MM) {
this.count = count;
this.database = database;
this.MM=MM;
}
}
Choice of dependency injection method
1. Force dependency to use constructors ( Constructor injection is a must , Otherwise, the object creation will not succeed , The configuration file will also report an error ) Conduct , Use setter Inject ( Optional ) There is a probability that not injecting will lead to null The object appears
2. Optional dependency use setter The injection goes on , Strong flexibility
3.Spring The framework advocates Guide using constructors , Most of the third-party frameworks use constructor injection for data initialization , Relatively rigorous
4. If necessary, you can use both at the same time , Use construction The injector completes the injection of mandatory dependencies , Use setter Injection completes the injection of optional dependencies
5. The actual development process should also be analyzed according to the actual situation , If the controlled object does not provide setter Method must be injected with a constructor
6. Self developed modules are recommended setter Inject
Rely on automatic assembly
* Automatic assembly :IOC Container basis bean The dependent resources are automatically found in the container and injected into bean The process of
* The way of automatic assembly (4 Kind of )
● By type ( Commonly used )
<bean id="bookService" class="com.GY.service.impl.BookServiceImpl " autowire="byType" />
● By name
<!-- Injected bean Of id( Here is bookDao) Need and set The formal parameter names of methods are consistent -->
<bean id="bookDao " class="com.GY.dao.impl.BookDaoImpl" >
<bean id="bookService" class="com.GY.service.impl.BookServiceImpl " autowire="byName" />
● According to the construction method ( It is not recommended to use )
● Automatic assembly is not enabled
* Rely on automatic assembly features
● Auto assembly is used to reference type dependency injection , Cannot operate on simple types
● When using assembly by type ( byType ) The same type of... In the container must be guaranteed bean only , Recommended
● When using assembly by name ( byName ) The container with the specified name must be guaranteed bean , This form is not good , Because variable names are coupled with configuration , It is not recommended to use
● The priority of automatic assembly is lower than setter Injection and constructor injection , The automatic configuration fails at the same time
Set injection
* Array
*List
*Set
*Map
*Properties
// Implementation class
public class BookDaoimpl implements BookDao {
private int[]array;
private List<String>list;
private Set<String>set;
private Map<String,String>map;
private Properties properties;
public void setArray(int[] array) {
this.array = array;
}
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public void save() {
System.out.println("book........");
System.out.println("①"+array);
System.out.println("②"+list);
System.out.println("③"+set);
System.out.println("④"+map);
System.out.println("⑤"+properties);
}
}
<!-- The configuration file -->
<bean id="BookDao" class="com.GY.BookDaoimpl" autowire="byType" >
<property name="array" >
<array>
<value>100</value>
<value>200</value>
<value>300</value>
</array>
</property>
<property name="list">
<list>
<value>GY,ghg,gf</value>
<value>buyuvycy</value>
</list>
</property>
<property name="map">
<map>
<entry key=" One " value="1"/>
<entry key=" Two " value="2"/>
</map>
</property>
<property name="properties">
<props>
<prop key="1"> One </prop>
<prop key="2"> Two </prop>
</props>
</property>
</bean>
result 
边栏推荐
- feign调用丢失请求头问题解决及原理分析
- 35.滚动 scroll
- Event Summary - common summary
- Laozi cloud and Fuxin Kunpeng achieved a major breakthrough in 3D ofd 3D format documents for the first time
- JDBC API 详解
- 2、 MySQL advanced
- Sub database and sub table
- Slashes / and backslashes involved in writing code\
- Explore the mysteries of the security, intelligence and performance of the universal altek platform!
- Detailed description of binary search tree
猜你喜欢

Could not autowire. No beans of ‘userMapper‘ type found.

JVM Part 1: memory and garbage collection part 3 - runtime data area - overview and threads

35. Scroll

Dialog introduction

1、 MySQL Foundation

精选用户故事|洞态在聚水潭的误报率几乎为0,如何做到?

idea远程调试debug

Read write separation and master-slave synchronization

Introduction to dynamic memory functions (malloc free calloc realloc)

JVM上篇:内存与垃圾回收篇五--运行时数据区-虚拟机栈
随机推荐
树莓派rtmp推流本地摄像头图像
Set static IP for raspberry pie
JVM上篇:内存与垃圾回收篇八--运行时数据区-方法区
[optical flow] - data format analysis, flowwarp visualization
QT menu bar, toolbar and status bar
Svn usage details
How to create an applet project
探寻通用奥特能平台安全、智能、性能的奥秘!
Use ngrok for intranet penetration
Row, table, page, share, exclusive, pessimistic, optimistic, deadlock
MySQL storage engine and its differences
素数筛选(埃氏筛法,区间筛法,欧拉筛法)
1、 MySQL Foundation
TypeScript 详解
Raspberry pie RTMP streaming local camera image
老子云携手福昕鲲鹏,首次实现3D OFD三维版式文档的重大突破
The provision of operation and maintenance manager is significantly affected, and, for example, it is like an eep command
Card drawing program simulation
Li Kou achieved the second largest result
Another skill is to earn 30000 yuan a month+