当前位置:网站首页>Bean operation domain and life cycle
Bean operation domain and life cycle
2022-07-07 10:02:00 【Youcan.】
Catalog
2.1.1 singleton Single case scope
2.1.2 prototype Prototype scope ( Multiple scope )
2.1.4 session Conversation scope
2.1.5 application Global scope ( Understanding can )
2.1.6 websocket( Understanding can )
3.1 Spring Execute the process
3.2.1 Instantiation ( Buy a house in the city )
3.2.2 Set properties ( decorate )
3.2.3 Bean initialization ( Buy all kinds of new furniture )
3.2.5 The destruction Bean( sell-out )
1. Bean Modified case
There is a public Bean ,A Users and B Shared by users , If A In use , Public resources Bean Revised , It can lead to B The user made an error while using .
A user (Controller9) When using, it is modified :
@Controller
public class UserController9 {
@Autowired
private User user1;
public User getUser() {
User user = user1;
user.setName(" Tang's monk ");
return user;
}
}
B user (Controller9) Use public resources :
@Controller
public class UserController10 {
@Autowired
private User user1;
public User getUser() {
return user1;
}
}public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
public class App {
public static void main(String[] args) {
// 1. obtain spring Context
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
UserController9 userController9 = context.getBean(UserController9.class);
System.out.println("Controller9 : " + userController9.getUser());
UserController10 userController10 = context.getBean(UserController10.class);
System.out.println("Controller10 : " + userController10.getUser());
}
}
Output :Controller9 : User{id=1, name=' Tang's monk ', password='123'}
Controller10 : User{id=1, name=' Tang's monk ', password='123'}In fact, we want Controller10 Output :Controller10 : User{id=1, name=' Zhang San ', password='123'}
public class App {
public static void main(String[] args) {
// 1. obtain spring Context
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
if(userController9 == userController9_2) {
System.out.println(" Memory addresses are equal , The singleton pattern ");
System.out.println(userController9);
System.out.println(userController9_2);
} else {
System.out.println(" Memory addresses are not equal , Not singleton mode ");
System.out.println(userController9);
System.out.println(userController9_2);
}
}
}
Output :
Memory addresses are equal , The singleton pattern
[email protected]
[email protected]Using singleton mode will greatly improve performance , therefore spring in Bean The default scope of is The singleton pattern (singleton). That is, all people use the same object .
2. Scope definition
After the occurrence of the above problems , Limits the available range of variables in the program , That is to define Scope .
Bean Scope of action Refer to Bean stay Spring Some kind of behavior pattern in the whole framework , For example, singleton scope , It means Bean Throughout Spring Only one of them , And it is shared globally , After others modify this value , What people behind read is the modified value .
2.1 Bean Of 6 Species scope
Spring The container is initializing a Bean When an instance of the , The scope of the instance is also specified .
1. singleton : Single case scope
2. prototype : Prototype scope ( Multiple scope )
3. request : Request scope
4. session : Conversation scope
5. application : Global scope
6. websocket :HTTP WebSocket Scope
The first two are Spring Core scope , The last four are Spring MVC Scope in
2.1.1 singleton Single case scope
describe : Under this scope Bean stay loC In the container There is only one instance : obtain Bean(applicationContext.getBean Other methods ) And assembly Bean ( adopt @Autowired notes ⼊) It's all the same thing .
scene : No state Of Bean Use this scope , Stateless means Bean The attribute state of the object No need to update
Spring The scope is selected by default
2.1.2 prototype Prototype scope ( Multiple scope )
describe : Every time you make a comparison of Bean All requests will Create a new instance : obtain Bean And assembly Bean Are instances of experience objects .
scene : A stateful Of Bean Use this scope
2.1.3 request Request scope
describe : Every time http Request meeting Create a new Bean example , Be similar to prototype
scene : once http Get requests and responses share Bean
stay SpringMVC Use in
2.1.4 session Conversation scope
describe : In a http session Define a Bean example
scene : Of the user session share Bean , such as : Record a user's login information
stay SpringMVC Use in
2.1.5 application Global scope ( Understanding can )
2.1.6 websocket( Understanding can )
Single case scope (singleton) and Global scope (application) The difference between :
The scope of the single case is Spring Core ( Common projects ) Scope of action , The global scope is Spring Web Scope in .
The scope of a singleton acts on loC The container of , and The global scope works on Servlet Containers .
2.2 Set scope
@Scope Tags can modify both methods and classes ,@Scope There are two settings :
1. Set the value directly :@Scope("prototype")
2. ( Constant ) Similar to enumeration settings :@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class UserBeans2 {
@Bean(name = "user1")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public User user1(){
User user = new User();
user.setId(1);
user.setName(" Zhang San ");
user.setPassword("123");
return user;
}
}
@Controller
public class UserController9 {
@Autowired
private User user1;
public User getUser() {
User user = user1;
user.setName(" Tang's monk ");
return user;
}
}public class App {
public static void main(String[] args) {
// 1. obtain spring Context
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
UserController9 userController9 = context.getBean(UserController9.class);
System.out.println("Controller9 : " + userController9.getUser());
UserController10 userController10 = context.getBean(UserController10.class);
System.out.println("Controller10 : " + userController10.getUser());
}
}
}
Output :Controller9 : User{id=1, name=' Tang's monk ', password='123'}
Controller10 : User{id=1, name=' Zhang San ', password='123'} 
modify UserBeans2 Code :
@Component
public class UserBeans2 {
@Bean(name = "user1")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public User user1(){
User user = new User();
user.setId(1);
user.setName(" Zhang San ");
user.setPassword("123");
return user;
}
}
Output :
Controller9 : User{id=1, name=' Tang's monk ', password='123'}
Controller10 : User{id=1, name=' Tang's monk ', password='123'}

3. Bean Principle analysis
3.1 Spring Execute the process
start-up Spring Containers -----》 Complete according to the configuration Bean initialization -----》Bean Object registered to Spring Containers in ( save )-----》 take Bean Assemble into the required class ( take )
3.2 Bean Life cycle
The whole life process of an object from birth to destruction .
1. Instantiation
2. Set properties
3. Bean initialization
4. Use Bean
5. The destruction Bean
3.2.1 Instantiation ( Buy a house in the city )
by Bean Allocate space . Instantiation is not equal to initialization , Just allocate memory space
3.2.2 Set properties ( decorate )
Execute the injection and assembly of dependent classes (A Need to use B Methods , Initialize first , And will B Load into the current class )
3.2.3 Bean initialization ( Buy all kinds of new furniture )
(1) Realize all kinds of Aware Notification method
(2) Execute initialization pre method
(3) Execute initialization method ( Two implementations : Annotation mode @PostConstruct or XML<bean init - method='xxx'>)
(4) Execute your own designated init - method Method
(5) Execute post initialization method
3.2.4 Use Bean( To stay in )
3.2.5 The destruction Bean( sell-out )
There are two realizations : Annotation mode @PreDestroy,XML<bean destroy - method='xxx'>

边栏推荐
- Basic chapter: take you through notes
- MongoDB创建一个隐式数据库用作练习
- 如何成为一名高级数字 IC 设计工程师(1-6)Verilog 编码语法篇:经典数字 IC 设计
- Pytest learning - dayone
- 2020 Zhejiang Provincial Games
- Strategic cooperation subquery becomes the secret weapon of Octopus web browser
- Please ask me a question. I started a synchronization task with SQL client. From Mysql to ADB, the historical data has been synchronized normally
- iNFTnews | 时尚品牌将以什么方式进入元宇宙?
- 基于智慧城市与储住分离数字家居模式垃圾处理方法
- Pit using BigDecimal
猜你喜欢
![[4g/5g/6g topic foundation -147]: Interpretation of the white paper on 6G's overall vision and potential key technologies -2-6g's macro driving force for development](/img/21/6a183e4e10daed90c66235bdbdc3bf.png)
[4g/5g/6g topic foundation -147]: Interpretation of the white paper on 6G's overall vision and potential key technologies -2-6g's macro driving force for development

【frida实战】“一行”代码教你获取WeGame平台中所有的lua脚本

Internship log - day07

Qualifying 3

Pytest learning - dayone

Impression notes finally support the default markdown preview mode

web3.0系列之分布式存储IPFS

JS逆向教程第一发

csdn涨薪技术-浅学Jmeter的几个常用的逻辑控制器使用

# Arthas 简单使用说明
随机推荐
根据热门面试题分析Android事件分发机制(一)
“十二星座女神降临”全新活动推出
请教个问题,我用sql-client起了个同步任务,从MySQL同步到ADB,历史数据有正常同步过去
ORM模型--数据记录的创建操作,查询操作
Delete a record in the table in pl/sql by mistake, and the recovery method
Strategic cooperation subquery becomes the secret weapon of Octopus web browser
conda离线创建虚拟环境
Check the example of where the initialization is when C initializes the program
The applet realizes multi-level page switching back and forth, and supports sliding and clicking operations
Performance optimization record of the company's product "yunzhujia"
[4g/5g/6g topic foundation-146]: Interpretation of white paper on 6G overall vision and potential key technologies-1-overall vision
Can't connect to MySQL server on '(10060) solution summary
中国首款电音音频类“山野电音”数藏发售来了!
终于可以一行代码也不用改了!ShardingSphere 原生驱动问世
PLC信号处理系列之开关量信号防抖FB
ORM--查询类型,关联查询
Arthas simple instructions
2020CCPC威海 J - Steins;Game (sg函数、线性基)
Write VBA in Excel, connect to Oracle and query the contents in the database
MySQL can connect locally through localhost or 127, but cannot connect through intranet IP (for example, Navicat connection reports an error of 1045 access denied for use...)