我一直在尝试弄清proxyScope如何以与this主题类似但不同的方式工作。
这是我的课程,正在玩的范围。每次创建对象或调用方法时,它都会打印日志:
@Component
public class SomeObject {
public SomeObject() {
System.out.println("Object created: " + hashCode());
}
public void someMethod() {
System.out.println("Method invoked: " + hashCode());
}
}
我的课程要保留对以上课程的引用:
@Component
public class BoxOne {
@Autowired
public SomeObject obj;
}
@Component
public class BoxTwo {
@Autowired
public SomeObject obj;
}
我的主要测试对象:
@SpringBootApplication
public class Test {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Test.class, args);
BoxOne box1 = context.getBean(BoxOne.class);
BoxTwo box2 = context.getBean(BoxTwo.class);
SomeObject obj1 = box1.obj;
SomeObject obj2 = box2.obj;
System.out.println("hashcode: " + obj1.hashCode());
System.out.println("hashcode: " + obj2.hashCode());
obj1.someMethod();
obj2.someMethod();
obj1.someMethod();
obj2.someMethod();
}
}
当我将范围设置为:
@Component
@Scope(value="singleton", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class SomeObject { ...
我得到日志:
Object created: 1481818223 (it's while context starting)
...
hashcode: 1508842159
hashcode: 1508842159
Method invoked: 1481818223
Method invoked: 1481818223
Method invoked: 1481818223
Method invoked: 1481818223
为什么在类外部调用的哈希码与在类内部调用的哈希码不同?
然后我将范围更改为:
@Component
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class SomeObject { ...
我得到日志:
hashcode: -1943188644
hashcode: -1943188644
Object created: 1076984738
Method invoked: 1076984738
Object created: 1810923540
Method invoked: 1810923540
Object created: 1581078471
Method invoked: 1581078471
Object created: 1932332324
Method invoked: 1932332324
我明白为什么每次调用一个方法都会创建新对象。我不明白的是:
为什么在上下文启动时没有创建bean的日志?
如果没有日志(因此没有创建任何bean),为什么hashCode方法返回值而不是NullPointerException?
为什么当我将其设置为原型时hashCode的两个结果都相同?
这个proxyMode有点奇怪,我怕我做错了...