当你觉得每次获取实例,只会返回给你同一个,或者每次获取实例,都会创建新的,这两种方式你都不满意的情况下,你就可以去自定义自己的作用域了。
我觉得这东西就和 facotrybean 一样,方便开发者来自定义一些创建逻辑,个性化的逻辑。
这里我想要实现一个功能:每次从容器中获取,都会给我返回一个这个实例的计数器,展示这个实例是第多个类下的实例。
大致步骤:
- 定义自定义的 scope
- 把自定义的 scope 注册到容器中
- 多次从容器中获取 bean,验证效果是否正常。
一、定义自定义的 scope
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
public class OneScope implements Scope {
private int index = 0;
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
System.out.println("get 被调用");
return new Student("skywalker-" + (index++), index);
}
@Override
public Object remove(String name) {
return null;
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return "";
}
}
二、为自己的实例设置自定义的 scope
@Component
@Scope("one")
public class Student {
private String name;
private int index;
public Student(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
三、测试验证
public class Application {
public static void main(String[] args) {
// 1、创建容器
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
// 2、注册 scope
context.getBeanFactory().registerScope("one", new OneScope());
context.register(MyConfig.class);
context.refresh();
// 3、多次获取 Bean
Student myBean = context.getBean(Student.class);
System.out.println("==>");
System.out.println(myBean.getName());
Student myBean2 = context.getBean(Student.class);
System.out.println(myBean2.getName());
}
}
执行结果
