Skip to content

Caution more strongly against using @ComponentScan in auto-configuration #15348

@bcalmac

Description

@bcalmac

Consider two mutually exclusive beans defined in a starter project:

@Component
@ConditionalOnBean(annotation = EnableSomething.class)
public class ZombieBean {
}

@Component
@ConditionalOnMissingBean(ZombieBean.class)
public class AlternateBean {
}

The natural expectation would be that when the application doesn't have @EnableSomething then AlternateBean exists and ZombieBean doesn't. However, in practice neither of them exists.

A project demonstrating the issue can be found at https://github.com/bcalmac/zombie-bean. Run mvn test and it should fail.

What seems to happen is that ZombieBean does not exist, but when @ConditionalOnMissingBean(ZombieBean.class) is evaluated, a ZombieBean exists in some zombie state and the conditional doesn't match.

   ZombieBean:
      Did not match:
         - @ConditionalOnBean (; SearchStrategy: all) did not find any beans annotated with io.github.bcalmac.zombiebean.starter.EnableSomething (OnBeanCondition)

   AlternateBean:
      Did not match:
         - @ConditionalOnMissingBean (types: io.github.bcalmac.zombiebean.starter.ZombieBean; SearchStrategy: all) found beans of type 'io.github.bcalmac.zombiebean.starter.ZombieBean' zombieBean (OnBeanCondition)

There are ways to refactor the auto-configuration and achieve the desired functionality, I'm submitting this primarily to question whether it is in some way an expected behavior.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions