Bean的三种生成方式和五种作用域范围
Bean的概念
Spring中Bean就是一个类的实例
<bean id="" class="" />通过构造器完成类的实例化
Bean的生成方式有三种:
1、构造器生成
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.hhh.pojo.User"></bean></beans>
@Test public void testConstrutor(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app2.xml"); User user = (User) applicationContext.getBean("user"); System.out.println(user); }
2、静态工厂
package com.hhh.util;import com.hhh.pojo.User;/** * @Author: hehehe * @Date: 2022/4/15 15:22 */public class UserFactory { public static User getUser(){ return new User(); }}
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user2" class="com.hhh.util.UserFactory" factory-method="getUser"></bean> </beans>
3、实例工厂
package com.hhh.util;import com.hhh.pojo.User;/** * @Author: hehehe * @Date: 2022/4/15 15:22 */public class UserFactory2 { public User getUser(){ return new User(); }}
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userFactory" class="com.hhh.util.UserFactory2"></bean> <bean id="user3" factory-bean="userFactory" factory-method="getUser"></bean></beans>
bean的作用域范围
scope有如下五个取值:
- singleton:单例的(默认的),使用singleton定义的Bean是单例的,每次调用getBean都是调用的同一个对象。只要IoC容器一创建就会创建Bean的实例。
- prototype:多例的,每次通过Spring IoC容器获取prototype定义的Bean时,容器都将创建一个新的Bean实例。创建时不会实例该Bean,只有调用getBean方法时,才会实例化。
- request:作用于web的请求范围,在每一次HTTP请求时,容器会返回Bean的同一个实例,对不同的HTTP请求则会产生一个新的Bean,而且该Bean仅在当前HTTP Request内有效。
- session:作用于web的会话范围,在一次HTTP Session中,容器会返回该Bean的同一个实例,对不同的HTTP请求则会产生一个新的Bean,而且该Bean仅在当前HTTP Session内有效。
- global-session:作用于集群环境的会话范围(全局会话范围),在一个全局的HTTP Session中,容器返回Bean的同一个实例。当不是集群环境时,它就是session。
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.hhh.pojo.User" scope="singleton"></bean></beans>
@Test public void testScope(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app3.xml"); //从容器中两次获得相同的id,判断两个实例是否相等,相等为单例,否则为多例 User user = (User) applicationContext.getBean("user"); User user2 = (User) applicationContext.getBean("user"); System.out.println(user==user2); }