Spring 中为 Bean 定义了多种作用域:
在 xml 配置文件中设置 Bean 的作用域需要在 bean 标签中设置 scope 属性。 为了验证 Bean 的实例被创建的次数,我们需要在构造函数中添加 println 函数,以确保该 Bean 被实例化一次。
配置文件
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置 Pen 的 Bean -->
<bean id="picasso" class="cn.edu.stu.Demo4.Bean.Pen" scope="singleton"
c:brand="picasso"
c:id="1"
c:price="169.05"/>
<!-- 配置 Student 的 Bean -->
<bean id="student" class="cn.edu.stu.Demo4.Bean.Student" autowire="byType" scope="prototype">
<constructor-arg name="id" value="19092701"></constructor-arg>
<constructor-arg name="name" value="张三"></constructor-arg>
<constructor-arg name="age" value="22"></constructor-arg>
<constructor-arg name="sex" value="true"></constructor-arg>
</bean>
</beans>
测试
@Test
public void Test1() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("BeanDemo4Context.xml");
Student stu1 = (Student)ctx.getBean("student");
Student stu2 = (Student)ctx.getBean("student");
Pen pen1 = (Pen)ctx.getBean("picasso");
Pen pen2 = (Pen)ctx.getBean("picasso");
System.out.println(stu1==stu2);
System.out.println(pen1==pen2);
}
运行结果
Create a new Pen Bean
Create a new Student Bean
Create a new Student Bean
false
true
在 java 配置文件中设置作用域你需要用到 @Scope 注解。
Java 配置文件
package cn.edu.stu.Demo4.Config;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import cn.edu.stu.Demo4.Bean.Pen;
import cn.edu.stu.Demo4.Bean.Student;
@Configuration
@ComponentScan("cn.edu.stu.Demo4.Bean")
public class StuConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public Pen picasso() {
Pen pen = new Pen(1,"picasso",163.05);
return pen;
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Student student() {
Student student = new Student(1,"李四",22,true);
return student;
}
}
测试
@Test
public void Test1() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(StuConfig.class);
Student stu1 = (Student)ctx.getBean("student");
Student stu2 = (Student)ctx.getBean("student");
Pen pen1 = (Pen)ctx.getBean("picasso");
Pen pen2 = (Pen)ctx.getBean("picasso");
System.out.println(stu1==stu2);
System.out.println(pen1==pen2);
}
结果
Create a new Pen Bean
Create a new Student Bean
Create a new Student Bean
false
true