当前位置:网站首页>Scope and lifecycle of beans
Scope and lifecycle of beans
2022-07-22 19:23:00 【Fly upward】
Catalog
1. The case shows Bean Scope problem
1.1 singletion: Single case scope
1.2 prototype: Prototype scope ( Multiple scope )
2.1 singletion: Simple interest scope
2.2 prototype: Prototype scope ( Multiple scope )
2.6 websocket:HTTP WebSocket do ⽤ Domain
1. The case shows Bean Scope problem
1.1 singletion: Single case scope
Suppose there are now ⼀ A public one Bean, Provide to A ⽤ Household and B ⽤ Household emissary ⽤, however ⽽ Making ⽤ On the way A ⽤ Huque “ quietly ” The public Bean The data of , Lead to B ⽤ Hu is making ⽤ It's timely ⽣ Unexpected logic error .
( Our expected result is , public Bean Can be in each ⾃ Is modified in the class of , But it cannot affect other classes )
Modified Bean Case study
public Bean
@Component
public class UserBeans {
@Bean
public User user1() {
User user1 = new User();
user1.setId(1);
user1.setName(" Huang Xiaoxiao ");
return user1;
}
}
A ⽤ Household emissary ⽤ when , Into the ⾏ Modified :
@Controller
public class BeanScopesController {
@Autowired
private User user1;
public User getUser1() {
User user = user1;
System.out.println("Bean primary name: " + user.getName());
user.setName(" Wen Tong ");
return user;
}
}
B ⽤ Then go to make ⽤ public Bean When :
@Controller
public class BeanScopesController2 {
@Autowired
private User user1;
public User getUser1() {
User user = user1;
return user;
}
}
Print A ⽤ Household and B ⽤ Household public Bean in Name Value :
public class App2 {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
BeanScopesController beanScopesController = context.getBean(BeanScopesController.class);
System.out.println("A After the object is modified Name:" + beanScopesController.getUser1().getName());
BeanScopesController2 beanScopesController2 = context.getBean(BeanScopesController2.class);
System.out.println("B Object acquisition Name: " + beanScopesController2.getUser1().getName());
}
}
Cause analysis
The reason for the above problems is Bean By default, it is the singleton state (singleton), That's all ⼈ The emissary of ⽤ All are the same ⼀ Objects .
send ⽤ A single case can be very ⼤ To some extent ⾼ performance , So in Spring in Bean Works of ⽤ The domain defaults to singleton The singleton pattern .
1.2 prototype: Prototype scope ( Multiple scope )
Directly in public Bean Add comments to @Scope("prototype") , Nothing else can be changed
@Component
public class UserBeans {
@Bean
@Scope("prototype") // Multiple scope
public User user1() {
User user1 = new User();
user1.setId(1);
user1.setName(" Huang Xiaoxiao ");
return user1;
}
}
see A and B Get object results
do ⽤ Domain definition
Limit the variable's ⽤ The scope is called as ⽤ Domain , In other words, an area in the source code that defines variables is called ⽤ Domain
⽽ Bean Works of ⽤ Domain means Bean stay Spring Something in the whole framework ⾏ For mode ,⽐ Such as singleton A single example is ⽤ Domain , It means Bean Throughout Spring There are only ⼀ Share , It is globally shared , So when other ⼈ After changing this value , So another way ⼀ What individuals read is the modified value .
2. 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 .Spring Yes 6 Species scope , The last four are based on Spring MVC Effective
1. singletion: Simple interest scope
2. prototype: Prototype scope ( Multiple scope )
3.request: Request scope
4.session: Callback scope
5.application: Global scope
6. websocket:HTTP WebSocket do ⽤ Domain
After attention 4 The state is Spring MVC The value in , In ordinary Spring term ⽬ Only the first two .
2.1 singletion: Simple interest scope
Officer, ⽅ explain :(Default) Scopes a single bean definition to a single object instance for each
Spring IoC container.
describe : The book ⽤ Under domain Bean stay IoC Only exist in container ⼀ An example : obtain Bean( That is, through
applicationContext.getBean etc. ⽅ Can't get ) And assembly Bean( That is, through @Autowired notes ⼊) It's all the same ⼀
Objects .
scene : Usually ⽆ State of Bean send ⽤ The book ⽤ Domain .⽆ State means Bean The property state of the object does not need to be updated
remarks :Spring This option is selected by default ⽤ Domain
2.2 prototype: Prototype scope ( Multiple scope )
Officer, ⽅ explain :(Default) Scopes a single bean definition to a single object instance for each
Spring IoC container.
describe : The book ⽤ Under domain Bean stay IoC Only exist in container ⼀ An example : obtain Bean( That is, through
applicationContext.getBean etc. ⽅ Can't get ) And assembly Bean( That is, through @Autowired notes ⼊) It's all the same ⼀
Objects .
scene : Usually ⽆ State of Bean send ⽤ The book ⽤ Domain .⽆ State means Bean The property state of the object does not need to be updated
remarks :Spring This option is selected by default ⽤ Domain
2.3 request: Request scope
describe : Every time http The request creates a new Bean example , Be similar to prototype
scene :⼀ Time http Sharing of requests and responses Bean
remarks : limit SpringMVC Chinese envoy ⽤
2.4 session: Callback scope
describe : stay ⼀ individual http session in , Definition ⼀ individual Bean example
scene :⽤ Sharing of user replies Bean, ⽐ Such as : Record ⼀ individual ⽤ Login information of the user
remarks : limit SpringMVC Chinese envoy ⽤
2.5 application: Global scope
describe : stay ⼀ individual http servlet Context in , Definition ⼀ individual Bean example
scene :Web Should be ⽤ Up and down ⽂ Information ,⽐ Such as : Record ⼀ One should ⽤ Share information for
remarks : limit SpringMVC Chinese envoy ⽤
2.6 websocket:HTTP WebSocket do ⽤ Domain
describe : stay ⼀ individual HTTP WebSocket Of ⽣ In the life cycle , Definition ⼀ individual Bean example
scene :WebSocket In every conversation , Save the ⼀ individual Map Structure header information , take ⽤ To wrap client messages
head . The first ⼀ After the first initialization , until WebSocket The end is the same ⼀ individual Bean.
remarks : limit Spring WebSocket Chinese envoy ⽤
2.7 A single example is ⽤ Domain (singleton) Work with the overall situation ⽤ Domain (application) difference
singleton yes Spring Core Works of ⽤ Domain ;application yes Spring Web The works in the book ⽤ Domain ;
singleton do ⽤ On IoC The container of ,⽽ application do ⽤ On Servlet Containers
3.Bean Principle analysis
Bean Of board ⾏ technological process (Spring Of board ⾏ technological process ):
start-up Spring Containers -> Instantiation Bean( Allocate memory space , from ⽆ To have )-> Bean Sign up to Spring in ( Save operation ) -> take Bean Assemble into the required class ( Take operation ).
4. Bean Life cycle
⽣ Life cycle refers to ⼀ Objects from birth ⽣ To destroy the whole ⽣ Life process , This process is called ⼀ Object's ⽣ Life cycle .
Bean Of ⽣ The life cycle is divided into the following 5 ⼤ part :
1. Instantiation Bean( by Bean Allocate memory space )
2. Set properties (Bean notes ⼊ And assembly )
3.Bean initialization
All kinds of Aware Notified ⽅ Law , Such as BeanNameAware、BeanFactoryAware、
ApplicationContextAware Of ⼝⽅ Law ;
Of board ⾏ BeanPostProcessor Initialization pre ⽅ Law ;
Of board ⾏ @PostConstruct initialization ⽅ Law , Depend on note ⼊ Be executed after operation ⾏;
Of board ⾏⾃⼰ designated init-method ⽅ Law ( If there is a designation );
Of board ⾏ BeanPostProcessor Post initialization ⽅ Law .
4. send ⽤ Bean
5. The destruction Bean
Destroy all kinds of containers ⽅ Law , Such as @PreDestroy、DisposableBean Interface method 、destroy-method
The difference between instantiation and initialization
Instantiation and property settings are Java Level system “ event ”, The operation process cannot ⼈⼯⼲ Pre and modification ;
⽽ Initialization is provided for developers , After instantiation , Class loading is completed before ⾏⾃ Definition “ event ” Handle .
Code demonstration of life cycle
//@Component
public class BeanLifeComponent implements BeanNameAware {
@PostConstruct
public void postConstruct() {
System.out.println(" perform @PostConstruct");
}
public void init() {
System.out.println(" perform init-method");
}
public void use() {
System.out.println(" Use bean");
}
@PreDestroy
public void preDestroy() {
System.out.println(" Yes @PreDestroy");
}
public void setBeanName(String s) {
System.out.println(" Yes Aware notice ");
}
}
xml The configuration is as follows :
<?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:content="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">
<content:component-scan base-package="com.beans"></content:component-scan>
<beans>
<bean id="beanLifeComponent" class="com.beans.BeanLifeComponent" init-method="init"></bean>
</beans>
</beans>
transfer ⽤ class :
public class App3 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
BeanLifeComponent beanLifeComponent = context.getBean("beanLifeComponent", BeanLifeComponent.class);
beanLifeComponent.use();
context.destroy();
}
}
边栏推荐
猜你喜欢
OSI seven layer network model
MFC dialog program only runs a simple example of a single instance
二、IDEA搭建JFinal項目+代碼自動生成+數據庫操作測試(三種方式)
场景实践 | 如何使用融云超级群构建游戏社区
服务器磁盘IO性能调优
用指针遍历数组
grafana面板-修改可视化文本和背景颜色
[yolov5 practice 4] traffic sign recognition system based on yolov5 - model test and evaluation
Audio 3A processing practice makes your application more "pleasant"
grafana面板-关于转换
随机推荐
MFC对话框程序只运行单个实例 的简单示例
Prototype object
Numpy.reshape finish image cutting
WGet downloads all files in the directory
Programmer interview golden code interview question 01.05. primary editing
Ps: how to call up auxiliary lines
[QT source code reuse] simulate the pop-up mode of qcompleter
什么是“实时”
记一次 .NET 某RFID标签管理系统 CPU 暴涨分析
Centos7 installs MySQL 5.7 decompressed version & Navicat connection MySQL & firewall settings - the personal test is valid
融云 x 幸识: 专属 00 后的真我社交自留地(内含抽奖)
Oracle容器数据库的安装和使用
Cross entropy loss function
Behind the explosion of collaborative office market: cloud communication capability is the focus of demand
MySQL execution process and sequence
Shell script debugging technology
Leetcode daily question 2021/12/27-2022/1/2
Date operation in shell script
LeetCode 每日一题 2022/2/7-2022/2/13
Leetcode daily question 2022/2/14-2022/2/20