@Configuration
public abstract Class C{
@Bean
protected abstract Object getObject();
}
@Configuration
Class A extends class C{
protected Object getObject(){
Map<String, String> object1 = new HashMap()<>;
object1.put(“key1”,”val1”);
return object1;
}
}
@Configuration
Class B extends class C{
protected Object getObject(){
Map<String, String> object2 = new HashMap()<>;
object2.put(“key2”,”val2”);
return object2;
}
}
当服务器启动时创建 Bean 时,类 A 和 B 都在调用 getObject() 时返回 object1。 我如何才能为不同的类返回不同的对象,看起来它们正在使用相同的 bean?
我尝试在抽象类方法上使用@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE),它仍然为两个方法调用返回object1。
您应该将 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) 添加到 getObject() 方法,如下所示
public abstract class ClassC {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
protected abstract Object getObject();
}