singleton和prototype是最常用的两种作用域,通过@Scope注解来实现
| 作用域 | 描述 |
|---|---|
| singleton | 默认的作用域,使用singleton定义的Bean在Spring容器中只有一个Bean实例 |
| prototype | Spring容器每次获取prototype定义的Bean,容器都将创建一个新的Bean实例 |
下面通过一个例子分析
- singleton作用域(默认)
创建TestController类
package annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import annotation.service.TestService;
@Controller("testController")
public class TestController {
public int a;//声明实例变量a
public void add(int a) {
this.a=a;
System.out.println("令a等于 "+this.a);
}
}
创建TestAnnotation类
package annotation;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import annotation.controller.TestController;
import annotation.dao.TestDaoImpl;
public class TestAnnotation {
public static void main(String[] args) {
// TODO 自动生成的方法存根
AnnotationConfigApplicationContext appCon= new AnnotationConfigApplicationContext(ConfigAnnotation.class);
TestController tc1 = (TestController)appCon.getBean("testController");
TestController tc2 = appCon.getBean(TestController.class);
System.out.println("tc1的地址:"+tc1);
System.out.println("tc2的地址:"+tc2);
tc1.add(1);
tc2.add(0);
System.out.println("实例tc1中a的值是"+tc1.a);
System.out.println("实例tc2中a的值是"+tc2.a);
appCon.close();
}
}
运行结果
tc1与tc2地址相同,说明是同一个Bean实例(一个类中只有一个实例)
先给a赋值为1,然后赋值为0,由于tc1和tc2只是同一个实例的两个不同别名,所以最终a的值都为0
- prototype作用域
创建TestController类
package annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import annotation.service.TestService;
@Controller("testController")
@Scope("prototype")
public class TestController {
public int a;
public void add(int a) {
this.a=a;
System.out.println("令a等于 "+this.a);
}
}
创建TestAnnotation类
package annotation;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import annotation.controller.TestController;
import annotation.dao.TestDaoImpl;
public class TestAnnotation {
public static void main(String[] args) {
// TODO 自动生成的方法存根
AnnotationConfigApplicationContext appCon= new AnnotationConfigApplicationContext(ConfigAnnotation.class);
TestController tc1 = (TestController)appCon.getBean("testController");
TestController tc2 = appCon.getBean(TestController.class);
System.out.println("tc1的地址:"+tc1);
System.out.println("tc2的地址:"+tc2);
tc1.add(1);
tc2.add(0);
System.out.println("实例tc1中a的值是"+tc1.a);
System.out.println("实例tc2中a的值是"+tc2.a);
appCon.close();
}
}
运行结果
显然tc1与tc2的地址不同,是两个不同的实例
故最终a的值不相同



