1 @Scope介绍和简单使用
Spring装配Bean默认是单例的,@Scope注解就可以配置该类是否是作业域
- singleton:默认,单例
- prototype:多例
- request:web环境下,每次请求
- session:web环境下,同一个Session是一个实例
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {
可见:可以作用在方法上和类上
将Person设置为单例,UserService为多实例
@Configuration
@ComponentScan(value = {"study.wyy.spring.anno.learn"})
public class MainConfig {
/**
* @Bean : 给容器中注册一个一个bean
* 类型为返回值类型
* id默认为方法名
*
*/
@Bean
@Scope("singleton")
Person person(){
Person kobe = new Person("Kobe", 20);
return kobe;
}
}
@Service
@Scope("prototype")
public class UserService {
public Person findPerson(){
return new Person("Wade", 12);
}
}
@Test
public void testScope(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person1 = applicationContext.getBean(Person.class);
Person person2 = applicationContext.getBean(Person.class);
UserService userService1 = applicationContext.getBean(UserService.class);
UserService userService2 = applicationContext.getBean(UserService.class);
Assert.assertThat(person1==person2,equalTo(true));
Assert.assertThat(userService1==userService2,equalTo(false));
}
3 加载时机
- 单例:默认是在创建容器的时候就会将将组件创建并装配到容器中
- 多例:使用的时候才会去创建组件
测试:为了测试,在做了一下改动
@Service
@Scope("prototype")
public class UserService {
public UserService() {
System.out.println("创建UserService");
}
public Person findPerson(){
return new Person("Wade", 12);
}
}
@ComponentScan(value = {"study.wyy.spring.anno.learn"})
public class MainConfig {
/**
* @Bean : 给容器中注册一个一个bean
* 类型为返回值类型
* id默认为方法名
*
*/
@Bean
@Scope("singleton")
Person person(){
System.out.println("创建Person");
Person kobe = new Person("Kobe", 20);
return kobe;
}
}
@Test
public void testScope2(){
System.out.println("创建IOC容器开始");
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
System.out.println("创建IOC容器结束");
Person person1 = applicationContext.getBean(Person.class);
UserService userService1 = applicationContext.getBean(UserService.class);
}
输出结果:
创建IOC容器开始
创建Person
创建IOC容器结束
创建UserService
可见Person在创建容器的时候已经被创建了
4 懒加载
如何让单例也实现懒加载:在使用的时候才会去创建: @Lazy
@ComponentScan(value = {"study.wyy.spring.anno.learn"})
public class MainConfig {
/**
* @Bean : 给容器中注册一个一个bean
* 类型为返回值类型
* id默认为方法名
*
*/
@Bean
@Scope("singleton")
@Lazy
Person person(){
System.out.println("创建Person");
Person kobe = new Person("Kobe", 20);
return kobe;
}
}
在测试
创建IOC容器开始
创建IOC容器结束
创建Person
创建UserService