类:
@Component @Scope("prototype") public class AnnotationTest { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void getName(){ System.out.println("调用方法"); } }
测试:
@RunWith(SpringRunner.class) @SpringBootTest public class SprinBootDmeoApplicationTests { @Test public void contextLoads() { } @Test public void annotation(){ ApplicationContext ac = new AnnotationConfigApplicationContext(AnnotationTest.class); AnnotationTest annotationTest1 = ac.getBean(AnnotationTest.class); annotationTest1.setAge(10); System.out.println("annotationTest1字节码:"+annotationTest1.hashCode());; //每次调用产生一个新的实列 AnnotationTest annotationTest2 = ac.getBean(AnnotationTest.class); annotationTest2.setAge(20); System.out.println("annotationTest2字节码:"+annotationTest2.hashCode());; System.out.println("实列对象annotationTest1的属性值:"+annotationTest1.getAge()); System.out.println("实列对象annotationTest1的属性值:"+annotationTest2.getAge()); } }
运行结果:
annotationTest1字节码:646204091
annotationTest2字节码:445010547
实列对象annotationTest1的属性值:10
实列对象annotationTest1的属性值:20
总结:
@Scope 定义bean的作用域
默认为singleton,还有prototype,session ,gloal session,required
singleton: 定义该bean是单例模式,在spring容器中,共享一个bean的实列
prototype:每次调用都会创建一个新的bean实列
required:每次请求都会创建一个新的bean实列