Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A shared library uses @ComponentScan to register its beans, and consuming applications get duplicate or unwanted beans. How should the library expose beans instead?

When a library uses @ComponentScan on its own packages, every consuming application picks up every annotated class in them, with no way to choose, so it gets duplicates, conflicts and beans it never wanted. A library should instead ship an auto-configuration class listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, guard each bean with @ConditionalOnMissingBean and property conditions so applications can override or turn it off, or offer an @Enable annotation that uses @Import. Classes created by that configuration should carry no stereotype annotations.

Why this question is asked

Shared libraries are where container problems spread fastest: one design decision in a common module affects every service that depends on it. Duplicate beans, a NoUniqueBeanDefinitionException after a version bump, or a scheduler nobody asked for starting in a service are all familiar symptoms of a library that scans itself. Interviewers ask this to see whether we know how Spring Boot's own starters solve the problem and can apply the same pattern. In this answer, we will see why self-scanning causes trouble, rebuild the library with auto-configuration, add conditions and properties, look at the @Enable alternative, and finish with how to migrate existing consumers.

1A Quick Recap: Scanning Versus Configuration

Component scanning finds classes annotated with @Component, @Service and the other stereotypes under given packages and registers each as a bean. Whoever owns the scan decides nothing about individual classes: every annotated class under the package is included.

Auto-configuration is Spring Boot's mechanism for libraries. A library lists configuration classes in a file inside its JAR, and Spring Boot loads them automatically when the JAR is on the classpath. Each configuration class decides, with conditions, whether to contribute its beans. That is how spring-boot-starter-data-jpa creates an EntityManagerFactory only when we have not defined our own.

2Why a Self-Scanning Library Causes Trouble

Here is the problematic library. Its configuration class scans the library's root package.

Java
// acme-audit library
@Configuration
@ComponentScan("com.acme.audit")
public class AuditConfig {}
package com.acme.audit; @Service public class AuditService { ... }
package com.acme.audit; @Component public class AuditCleanupScheduler { ... } // @Scheduled every 5 min
package com.acme.audit; @Component public class JacksonAuditModule extends SimpleModule { ... }
package com.acme.audit.test; @Component public class InMemoryAuditStore implements AuditStore { ... }
// Consumer: "Parameter 0 of constructor in AuditService required a single bean,
// but 2 were found: jdbcAuditStore, inMemoryAuditStore"

Several things go wrong at once. The consumer gets every component, including the cleanup scheduler it may not want and a test helper that was never meant for production. When the consumer also scans com.acme because its own code lives there, the same classes can be found twice. The Jackson module silently changes JSON serialisation for the whole application. And none of it can be turned off without excludeFilters in the consumer's code, which couples the consumer to the library's package layout. Adding a new @Component in the next library version changes every consumer's context without warning.

3The Fix: An Auto-Configuration Class

We remove @ComponentScan and the stereotype annotations, and declare the beans explicitly in an auto-configuration class. The class is annotated with @AutoConfiguration and listed in the imports file. Note that the file name is the full path META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, with one class name per line; the older spring.factories registration for auto-configurations was removed in Spring Boot 3.

Java
@AutoConfiguration(after = DataSourceAutoConfiguration.class)
@ConditionalOnProperty(prefix = "acme.audit", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties.class)
public class AuditAutoConfiguration {
@Bean @ConditionalOnMissingBean(AuditStore.class)
@ConditionalOnBean(DataSource.class)
AuditStore jdbcAuditStore(DataSource ds) { return new JdbcAuditStore(ds); }
@Bean @ConditionalOnMissingBean
AuditService auditService(AuditStore store, AuditProperties props) {
return new AuditService(store, props.retention());
}
@Bean @ConditionalOnProperty(prefix = "acme.audit.cleanup", name = "enabled") // off unless asked
AuditCleanupScheduler auditCleanupScheduler(AuditService audit) { return new AuditCleanupScheduler(audit); }
}
# src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.acme.audit.autoconfigure.AuditAutoConfiguration
Step throughHow the auto-configuration decides
  1. Is acme.audit.enabled false?
    YesContribute nothingNoGo on
  2. Has the application defined its own AuditStore?
    YesUse the application's storeNoCreate JdbcAuditStore
  3. Has the application defined its own AuditService?
    YesUse the application's serviceNoCreate AuditService
  4. Is acme.audit.cleanup.enabled true?
    YesCreate the schedulerNoNo scheduler

4 steps in order. Play them, or step through them one at a time.

Notice what each condition does. @ConditionalOnMissingBean means that if the application defines its own AuditStore or AuditService, the library's version steps aside, so overriding is just declaring a bean. The property conditions let an application switch the whole feature off, acme.audit.enabled=false, or turn on optional parts such as the scheduler. The test-only in-memory store moves to a separate test artifact, and the Jackson module becomes an opt-in bean too.

4The Alternative: An @Enable Annotation

Some libraries should only be active when an application asks for them explicitly, even if the JAR is on the classpath for another reason. For those, an @Enable annotation that uses @Import is a good fit. The consumer adds @EnableAcmeAudit to a configuration class, and the import brings in the library's configuration. This is the same pattern Spring uses for @EnableScheduling and @EnableCaching.

Java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(AuditConfiguration.class) // a plain @Configuration with explicit @Bean methods
public @interface EnableAcmeAudit {}
@SpringBootApplication
@EnableAcmeAudit // opt-in, visible in the application code
public class OrdersApp { ... }

The choice between the two is about defaults. Auto-configuration suits libraries whose whole point is to be active when present, like a starter. An @Enable annotation suits features that change behaviour noticeably and should be a visible decision in the consumer's code.

5Keeping Library Classes Plain, and Migrating Consumers

Once beans are created by configuration, the classes themselves should not carry @Service or @Component. If they do, any consumer that happens to scan the library's package, for example because it uses the same com.acme prefix, gets a second copy, and the duplicate-bean problem returns. Plain classes with constructor injection are also easier to test and to use outside Spring.

To migrate, release a version that adds the auto-configuration while keeping the old config class deprecated, announce the change and the new properties, and remove @ComponentScan in the next major version. A test with Spring Boot's ApplicationContextRunner should cover the important cases: default beans present, a user-defined AuditStore wins, the property switch removes everything, and the scheduler only appears when enabled.

Java
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class))
.withBean(DataSource.class, () -> mock(DataSource.class))
.withPropertyValues("acme.audit.enabled=false")
.run(ctx -> assertThat(ctx).doesNotHaveBean(AuditService.class)); // passes

6Follow-up questions

Why not just tell consumers to add excludeFilters?

Because it moves the library's internal structure into every consumer. Each team must know which classes to exclude, and a new component in the next library version silently appears in their context. Conditions inside the library let the library own its defaults and give consumers a small, documented set of switches.

What does @ConditionalOnMissingBean need to work correctly?

It is evaluated in order, so it must run after the application's own beans are registered. Auto-configurations are processed after user configuration, which is why the condition is reliable there. Inside an ordinary user @Configuration class it can give surprising results, which is another reason to put such beans in auto-configuration.

Should every internal library be a starter?

Libraries that contribute beans usually benefit from it. Pure utility libraries with no beans do not need any Spring integration. A common pattern is a core module with plain classes and a separate autoconfigure or starter module that wires them, so non-Spring users can use the core alone.

7Conclusion

In this answer, we saw that a library that uses @ComponentScan forces every annotated class on its consumers, who cannot control what they get, which causes duplicate and unwanted beans. The fix is an auto-configuration class listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, with beans guarded by @ConditionalOnMissingBean and property conditions so applications can override or disable them. An @Enable annotation with @Import is the alternative for opt-in features, and library classes created by configuration should carry no stereotype annotations.

What to say in the interviewAbout 80 seconds aloud

Open with

The core problem is that @ComponentScan in a library hands every annotated class in that package to every consumer, with no way to choose. So consumers get beans they did not ask for, like a scheduler or a test helper, duplicates when their own scan also covers the same package prefix, and NoUniqueBeanDefinitionException when the library ships two implementations of one interface.

Then, if they want more

And a new component in the next version changes everyone's context silently. I would restructure the library the way Spring Boot's own starters work. Remove @ComponentScan and the stereotype annotations, and declare the beans explicitly with @Bean methods in an @AutoConfiguration class, listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.

Each bean gets @ConditionalOnMissingBean, so an application overrides it just by defining its own, and the feature gets property conditions, an enabled switch that defaults to true and opt-in switches for optional parts like the scheduler. If the feature should be an explicit decision in the consumer's code, I would offer an @EnableAcmeAudit annotation that uses @Import instead.

Finally I would keep the library classes free of @Component so accidental scanning cannot duplicate them, test the conditions with ApplicationContextRunner, and migrate consumers over a deprecation release before removing the old scan.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A shared library uses @ComponentScan to register its beans, and consuming applications...": https://scrivio-interview-library.netlify.app/spring-boot/ioc-container/8d8a5265e7/