提示:注意一个区别,如果是单例的,IOC容器启动的时候就会创建bean;如果是多例的,IOC容器在调用这个bean的时候才会创建bean,这可能是一个面试点
1、配置类,默认是单例
@Configuration
public class DemoConfig {
@Bean("person")
public Person getPerson(){
return new Person(1,"123",12);
}
}
验证
public class DemoApp {
public static void main(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoConfig.class);
Person person = (Person)applicationContext.getBean("person");
Person person2 = (Person)applicationContext.getBean("person");
System.out.println(person == person2);
}
}
//结果是ture,证明默认是单例的
2、使用@scope配置多例
scope的注释
/**
* Specifies the name of the scope to use for the annotated component/bean.
* <p>Defaults to an empty string ({@code ""}) which implies
* {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
* @since 4.2
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE:单例
* @see ConfigurableBeanFactory#SCOPE_SINGLETON:多例
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST:
主要针对web应用,提交一个请求创建一个实例
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION;
同一个session创建一个实例
* @see #value
*/
@AliasFor("value")
String scopeName() default "";
配置类
@Configuration
public class DemoConfig {
@Scope("prototype")
@Bean("person")
public Person getPerson(){
return new Person(1,"123",12);
}
}
此时验证类输出为true