- 默認情況下是單例模式(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域中)