Scope_prototyped bean is instantiated at startup and fails because it can't autowire

Viewed 70

I want to create a prototyped bean with some custom parameter using an ObjectFactory. At the place where I need my bean I have the following:

private final ObjectProvider<Installation> installationProvider;

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

and I have it configured like that:

@Configuration
public class MyConfiguration {

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

But when I start my application I get the following exception:

***************************
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.

Given that this is occurring at startup it seems like Spring tries to autowire this bean at startup. However, my understand is that a a bean of scope SCOPE_PROTOTYPE should not be autowire at runtime, as I want to create the beans during runtime with different parameters.

2 Answers

I found the problem. I had a separate service which I created for testing a while ago (and forgot about):

@Service
public class TestSomething {
    private final Installation installation;

    @Autowired
    public TestSomething(Installation installation) {
        this.installation = installation;
    }
}

As this service is wired at startup, obviously it will also try to autowire the dependen bean.

I've setup a sample project like yours and it works as expected. Every call to installationProvier.getObject("url") return a new instance of the installtaion bean.

Are you sure, that your application don't access the bean via @Autowire in another class?

Related