【问题标题】:Scope_prototyped bean is instantiated at startup and fails because it can't autowireScope_prototyped bean 在启动时被实例化并失败,因为它不能自动装配
【发布时间】:2020-10-30 12:24:23
【问题描述】:

我想使用ObjectFactory 创建一个带有一些自定义参数的原型bean。在我需要 bean 的地方,我有以下内容:

private final ObjectProvider<Installation> installationProvider;

public void test() {
  Installation installation = installationProvider.getObject("url");
}

我已经这样配置了:

@Configuration
public class MyConfiguration {

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public Installation createInstallation(String url) {
        return new Installation(url);
    }
}

但是当我启动我的应用程序时,我得到了以下异常:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method createInstallation in com.mycompany.MyConfiguration required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

鉴于这是在启动时发生的,似乎 Spring 试图在启动时自动装配这个 bean。但是,我的理解是,SCOPE_PROTOTYPE 范围的 bean 不应该在运行时自动装配,因为我想在运行时使用不同的参数创建 bean。

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    我发现了问题。我有一个单独的服务,我在不久前创建了一个用于测试的服务(并且忘记了):

    @Service
    public class TestSomething {
        private final Installation installation;
    
        @Autowired
        public TestSomething(Installation installation) {
            this.installation = installation;
        }
    }
    

    由于此服务在启动时已连接,显然它也会尝试自动连接依赖的 bean。

    【讨论】:

      【解决方案2】:

      我已经设置了一个像您这样的示例项目,它按预期工作。每次调用 installationProvier.getObject("url") 都会返回一个新的 installtaion bean 实例。

      您确定您的应用程序不会通过另一个类中的@Autowire 访问 bean 吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-06
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多