@Scope示例如下:
1、创建一个maven项目(创建maven项目过程省略),pom.xml文件引入如下依赖:
org.springframework
spring-context
5.2.0.RELEASE
junit
junit
4.12
test
2、创建一个person的实体类,代码如下:
package com.rf.bean;
public class PersonBean {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "PersonBean [id=" + id + ", name=" + name + "]";
}
public PersonBean(String id, String name) {
super();
this.id = id;
this.name = name;
}
public PersonBean() {
super();
}
}
3、创建一个配置类,把Scope属性改成singleton 的代码如下;
package com.rf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import com.rf.bean.PersonBean;
@Configuration //标记这是一个配置类
public class MyConfig {
//默认单实例
/**
* 指定要用于带注释的组件/bean的作用域的名称。
* singleton 单实例(默认值),ioc容器启动就会调用方法创建对象放到ioc容器中,
* 以后每次获取直接从容器中拿。
* prototype 多实例 ,ioc容器启动并不会去调用方法创建对象放在容器中,
* 每次获取的时候才会调用方法创建对象
* request 在web应用中,同一次请求创建一个实例
* session 在web应用中,同一个session创建一个实例
* */
@Scope//如果不设置属性,默认单实例
@Bean("person")
public PersonBean person(){
System.out.println("给容器中添加bean。");
return new PersonBean("2","李四");
}
}
4、编写测试类,代码如下:
package com.rf.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.rf.config.MyConfig;
public class Test {
@org.junit.Test
public void test02(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println("ioc容器创建完成。");
Object bean1 = applicationContext.getBean("person");//bean的id获取实例
Object bean2 = applicationContext.getBean("person");
System.out.println(bean1==bean2);
}
}
5、启动测试类,运行效果如下: 6、把配置类Scope的属性改成prototype 的代码如下;
package com.rf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import com.rf.bean.PersonBean;
@Configuration //标记这是一个配置类
public class MyConfig {
//默认单实例
/**
* 指定要用于带注释的组件/bean的作用域的名称。
* singleton 单实例(默认值),ioc容器启动就会调用方法创建对象放到ioc容器中,
* 以后每次获取直接从容器中拿。
* prototype 多实例 ,ioc容器启动并不会去调用方法创建对象放在容器中,
* 每次获取的时候才会调用方法创建对象
* request 在web应用中,同一次请求创建一个实例
* session 在web应用中,同一个session创建一个实例
* */
@Scope("prototype")
@Bean("person")
public PersonBean person(){
System.out.println("给容器中添加bean。");
return new PersonBean("2","李四");
}
}
7、再次启动测试类,运行效果如下: