- 默认情况下是单例模式(singleton),单例模式 特点是ioc容器创建完成就会将bean加入ioc容器中
- 如果通过@Scope改成多实例模式(prototype)特点是在ioc容器创建后不会直接创建bean加入到ioc容器,而是在调用获取bean的时候创建bean加入ioc容器
单例模式证明:
bean类
package bean;
public class HelloWorld {
String hello="Hello demo";
public HelloWorld() {
super();
}
@Override
public String toString() {
return "HelloWorld{" +
"hello='" + hello + '\'' +
'}';
}
}
spring配置类
package config;
import bean.HelloWorld;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean("hello")
public HelloWorld hello() {
System.out.println("bean加入ioc容器");
return new HelloWorld();
}
}
单元测试类
package config;
import bean.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.Assert.*;
public class ConfigTest {
@Test
public void test1(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
// HelloWorld hello = (HelloWorld) applicationContext.getBean("hello");
// System.out.println("bean创建成功");
// System.out.println(hello);
}
}
默认情况下单例模式运行单元测试会输出bean加入ioc容器表示配置类代码执行了
多实例模式证明:
修改上面的配置类加入@Scope注解
package config;
import bean.HelloWorld;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class Config {
@Scope("prototype")//多实例模式
@Bean("hello")
public HelloWorld hello() {
System.out.println("bean加入ioc容器");
return new HelloWorld();
}
}
可以发现运行结果不会执行配置类中加入@Scope("prototype")注解标注的方法
将后面获取的bean的注释去掉重新运行一遍,会发现在获取bean的时候才会执行@Scope标注的方法
并且在前面的基础上会发现每次获取的bean都是重新获取的bean,并且两个bean不是同一个bean 。
另外需要注意的是@Scope注解除了填singleton和prototype外在web中还有request和session,不过这两个一般不会使用(一般放在请求域中或者session域中)