2 回答

TA貢獻1848條經驗 獲得超10個贊
異常說明了一切 - attribute1 bean 是在應用程序初始化期間創建的(通過會話作用域 bean),但沒有與請求綁定的線程。您還應該代理您的 attribute1 bean,因為您將其注入到單例(屬性 2 服務。)

TA貢獻1853條經驗 獲得超9個贊
基于 Alexander.Furer 給出的見解。我創建了自己的作用域,并管理它來調用 bean 提供者,以便在Attribute1方法的每次訪問中都擁有新鮮的 bean。
為此,我擴展了以下范圍:
// Register scope as "runtime"
public class RuntimeScope implements Scope {
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
return objectFactory.getObject();
}
...
}
新Attribute1服務:
@Service
public class Attribute1Service {
@Resource
private BeanSession beanSession;
public void setDefaultValue() {
Configuration configuration = beanSession.getRootState();
configuration.getAttribute1().setValue("VALUE 1");
}
@Bean
@Scope(value = "runtime", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Attribute1 attribute1() {
Configuration configuration = beanSession.getRootState();
return configuration.getAttribute1();
}
}
消費者Attribute2服務:
@Service
public class Attribute2Service {
@Resource
private BeanSession beanSession;
@Resource
private Processor processor;
@Resource
private Attribute1 attribute1;
public void defineAttribute2() {
Configuration configuration = beanSession.getRootState();
String value = processor.getValue(configuration, attribute1.getValue()); // Will call Attribute1 service to require the fresh bean
configuration.getAttribute2().setValue(value);
}
public void defineAttribute3() {
Configuration configuration = beanSession.getRootState();
String value = processor.getValue(configuration, attribute1.getValue()); // Will call Attribute1 service to require the fresh bean
configuration.getAttribute3().setValue(value);
}
}
我沒有看到的問題是 Attribute1 應該是處理 bean 實例化的代理。因此,通過創建我自己的范圍,我可以保證訪問 attribute1(由Attribute2Servicewith生成attribute1.getValue())方法將創建一個新的 bean(由 提供Attribute1Service)。
添加回答
舉報