package com.lei.study_09_13.bean; /** * * * @author LeiLei * @date 2019/9/13 */ public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { this.name = name; this.age = age; } public Person() { } @Override public String toString() { return "Person56{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
package com.lei.study_09_13.config; import com.lei.study_09_13.bean.Person; import org.springframework.context.annotation.*; /** * * * @author LeiLei * @date 2019/9/13 */ @Configuration public class BeanConfig2 { /** * rototype 多实例 使用时初始化 * singleton 单实例 使用前初始化并放入容器 * request 一次请求创建一个实例(不使用、一般直接放在request域中即可) * session 一次会话创建一个实例(不使用、一般直接放在session域中即可) */ @Scope("prototype") @Bean public Person person() { System.out.println("person初始化完成。。。"); return new Person("小明",24); } }
package com.lei; import com.lei.study_09_13.bean.Person; import com.lei.study_09_13.config.BeanConfig; import com.lei.study_09_13.config.BeanConfig2; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.Arrays; import org.junit.Test; /** * * * @author LeiLei * @date 2019/9/13 */ public class TestAnno { @Test public void testScope() { ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig2.class); System.out.println("容器初始化完成。。。"); Person person = context.getBean(Person.class); // System.out.println("person:"+person); Person person2 = context.getBean(Person.class); // System.out.println("person2:"+person2); // System.out.println(person == person2); } @Test public void testCompontScan() { ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class); String[] names = context.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } } }
总结:
1.@Scope注解标注组件实例化的范围
* rototype 多实例 使用时初始化 * singleton 单实例 使用前初始化并放入容器 * request 一次请求创建一个实例(不使用、一般直接放在request域中即可) * session 一次会话创建一个实例(不使用、一般直接放在session域中即可)