Skip to content

Avoid creation of lazy candidates when the primary bean is injected [SPR-14611] #19178

Closed

Description

@spring-projects-issues

Asaf Romano opened SPR-14611 and commented

Consider the following code in a Config class:

    @Bean(name = "sharedExecutorService")
    @Primary
    @Lazy
    public ExecutorService sharedExecutorService()
    {
        System.out.println("In sharedExecutorService");
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        System.out.println(String.format("Created: %s", executorService));
        return executorService;
    }

    @Bean(name = "localExecutorService1")
    @Lazy
    public ExecutorService localExecutorService1()
    {
        System.out.println("In localExecutorService1");
        ExecutorService executorService = sharedExecutorService();
        System.out.println(String.format("Created: %s", executorService));
        return executorService;
    }

    @Bean(name = "localExecutorService2")
    @Lazy
    public ExecutorService localExecutorService2()
    {
        System.out.println("In localExecutorService2");
        ExecutorService executorService = sharedExecutorService();
        System.out.println(String.format("Created: %s", executorService));
        return executorService;
    }

Later on, someone injects the primary bean as follows:

@Inject
private ExecutorService executorService;

The expectation is for the primary bean to be constructed and injected at this point, but for the other two beans not to be constructed yet (as they are lazy). What seems to happen, however, is that all three beans are constructed at this point (albeit the primary bean is successfully injected).

Please note that this issue seems to be quite similar to #18314


Affects: 4.3.2

Issue Links:

Referenced from: commits c4fcdb6, a7849b2

Activity

  1. spring-projects-issues commented on Aug 24, 2016

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    I've addressed this through a revision of DefaultListableBeanFactory's resolution algorithms, only resolving bean instances when already available and otherwise operating against the bean type until an instance has actually been selected for exposure. This still allows for proper introspection of primary candidates and priority values but does not trigger unnecessary bean creation.

  2. added
    type: enhancement
    in: core
    on Jan 11, 2019
  3. added this to the 4.3.3 milestone on Jan 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: coretype: enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions