Spring按需创建原型Bean并引用稍后创建的Bean

Spring按需创建原型Bean并引用稍后创建的Bean,spring,spring-boot,spring-aop,Spring,Spring Boot,Spring Aop,我是spring的新手,我正在尝试修改我的应用程序以实现spring框架。 我的请求是为每个新请求创建一个新bean,然后在代码后面引用该bean,以便从单例bean为其设置值。 我试图将bean声明为原型,并使用查找方法在我的单例bean中引用该bean。 但我的问题是,当稍后尝试获取创建的原型bean以设置值时,我看到它在获取bean时再次创建新bean @Component public class PersonTransaction { @Autowired Perso

我是spring的新手,我正在尝试修改我的应用程序以实现spring框架。 我的请求是为每个新请求创建一个新bean,然后在代码后面引用该bean,以便从单例bean为其设置值。 我试图将bean声明为原型,并使用查找方法在我的单例bean中引用该bean。 但我的问题是,当稍后尝试获取创建的原型bean以设置值时,我看到它在获取bean时再次创建新bean

@Component
public class PersonTransaction {

    @Autowired
    PersonContext btContext;
    @Autowired
    PersonMapper personMapper;

    public void setPersonMapper(PersonViewMapper personMapper) {
        this.personMapper = personMapper;
    }

    public PersonBTContext createContext() throws ContextException {
        return btContext = getInitializedPersonBTInstance();
    }

    private PersonBTContext getContext() throws ContextException{
        return this.btContext;
    }

    public void populateView(UserProfileBean userProfile) throws ContextException {
        personMapper.populateView(userProfile,getContext());
    }

    @Lookup(value="personContext")
    public  PersonBTContext getInitializedPersonBTInstance(){
        return null;
    }
}
下面是我的原型课程

@Component("personContext")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PersonContext extends ReporterAdapterContext {
    private List<Person> persons = null;
    private Person person = null;
    private List<String> attributes = null;

    private boolean multiplePersons = false;
    private boolean attributeSelected = false;

    public boolean isMultiple() {
        return multiplePersons;
    }

    public boolean isAttributeSelected() {
        return attributeSelected;
    }

    private void setAttributeSelected(boolean attributeSelected) {
        this.attributeSelected = attributeSelected;
    }

    // remaining getters/setters

    }
当我从singleton PersonTransaction类调用createContext时,它应该创建新的原型bean,以后如何通过调用getContext方法来获取创建的原型bean?我想,btContext正在再次返回新bean

稍后需要帮助获取创建的原型bean以设置值


感谢您的帮助。

您想要创建请求范围的bean,而不是原型范围的bean。看一看哪个描述了不同的bean范围,包括请求范围:

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public PersonContext personContext() {
  return new PersonContext();
}

这应该可以简化您的逻辑,只要您可以在处理请求后丢弃bean。

我的是一个Web服务应用程序,当我尝试将其设置为请求范围时,其抛出错误表示,范围“request”对于当前线程不活动;如果您想从一个bean中引用它,请考虑为它定义一个作用域代理。singleton@marc请求范围通常是开箱即用的。如果您有自定义web配置,请尝试。