Annotation-Based Configuration & Component Scanning practice questions

From Spring Certified Professional (Develop) (2V0-72.22) · 18 questions on this topic

Annotation-Based Configuration & Component Scanning practice questions from Spring Certified Professional (Develop) (2V0-72.22). This pack has 18 questions tagged Annotation-Based Configuration & Component Scanning, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Annotation-Based Configuration & Component Scanning

  1. Question 1

    When is a method annotated @PreDestroy invoked for a singleton bean?

    1. A. During container shutdown, just before the bean is destroyedCorrect answer

      Correct: @PreDestroy is a JSR-250 destruction callback the container runs as it closes, just before a singleton is disposed, making it the place to release resources (Spring Framework 5.3 Reference, @PostConstruct and @PreDestroy).

    2. B. Immediately after @PostConstruct completes

      Confuses the two lifecycle ends: @PostConstruct runs after initialization while @PreDestroy runs at teardown, so they are not chained back-to-back.

    3. C. Never for singletons; only prototypes get @PreDestroy

      Exactly reversed: singletons do receive the callback at container shutdown, whereas prototype beans are the ones that get no destruction callbacks at all since the container does not manage their full lifecycle.

    4. D. After every method invocation on the bean

      It is a one-time teardown hook, not a per-invocation interceptor; the method fires once as the bean is destroyed, not after each call.

    Explanation

    @PreDestroy is a one-time JSR-250 teardown callback that the container runs as it closes, just before a managed singleton is disposed, which is why it is used to release resources. It is tied to destruction rather than to initialization or per-method invocation, and it is singletons — not prototypes — that receive it.

  2. Question 2

    Beyond making a class a scannable Spring component, what additional behavior does @Repository enable?

    1. A. It registers the class as a Spring Data repository proxy

      Incorrect. It confuses the stereotype with Spring Data: repository proxies come from extending Spring Data's Repository interfaces, not from applying the @Repository annotation.

    2. B. Persistence exception translation — native/vendor exceptions are converted into Spring's DataAccessException hierarchyCorrect answer

      Correct. Together with a PersistenceExceptionTranslationPostProcessor, @Repository makes the bean eligible for persistence-exception translation, converting native/vendor exceptions into Spring's unchecked DataAccessException hierarchy (Spring Framework 5.3 Reference, stereotype annotations & exception translation).

    3. C. It makes every method of the bean transactional automatically

      Incorrect. Transactional behavior comes from @Transactional; the @Repository stereotype adds no transaction semantics.

    4. D. It changes the bean's scope to prototype

      Incorrect. The stereotype does not alter bean scope; the default singleton scope is unchanged.

    Explanation

    @Repository is a stereotype that, in combination with a PersistenceExceptionTranslationPostProcessor, makes a persistence bean eligible for exception translation: native or vendor-specific data-access exceptions are converted into Spring's unchecked DataAccessException hierarchy. This is distinct from transaction management, from Spring Data's proxy generation, and from bean scope, none of which the annotation affects.

  3. Question 3

    Which TWO statements accurately describe how @ComponentScan behaves in Spring Framework 5.3? Select TWO.

    1. A. With no basePackages attribute specified, it scans the package of the annotated configuration class and all of its sub-packages.Correct answer

      The default base package is the package of the class declaring @ComponentScan, and scanning recurses into sub-packages (Spring Framework 5.3 Reference — component scanning base packages).

    2. B. It discovers @Bean methods declared in the scanned classes and registers each one as a bean definition.

      Component scanning detects annotated component classes, not @Bean factory methods; @Bean registration is a separate mechanism handled by processing the configuration class itself.

    3. C. It detects @Service, @Repository, and @Controller classes because each of those is meta-annotated with @Component.Correct answer

      The stereotypes are specializations meta-annotated with @Component, so component scanning auto-detects them alongside plain @Component classes.

    4. D. It reads and registers bean definitions from any XML bean-definition files it finds on the classpath.

      Component scanning never parses XML; loading XML bean definitions into a Java-config context is the job of @ImportResource.

    5. E. It automatically picks up every @Configuration class anywhere on the classpath, regardless of package.

      Only configuration within the scanned base packages (or explicitly registered/imported) is processed; there is no classpath-wide automatic discovery of @Configuration classes.

    Explanation

    When no base package is given, @ComponentScan scans the annotated class's own package and its sub-packages, and it detects the stereotype annotations because each is meta-annotated with @Component. It does not register @Bean methods (a separate configuration-processing step), does not read XML (that is @ImportResource), and does not sweep the whole classpath for @Configuration classes.

  4. Question 4

    Why is field injection (@Autowired directly on a private field) generally discouraged?

    1. A. It does not work on classes annotated @Component

      False premise: field injection works perfectly well on @Component-annotated classes; the objection to it is about maintainability and testability, not about whether it functions.

    2. B. It hides dependencies, prevents final fields, and makes the class hard to instantiate/test outside the Spring containerCorrect answer

      Correct: field injection obscures a class's true dependencies, cannot populate final fields, and forces reflection or the container to construct the object for testing — the maintainability reasons the reference discourages it (Spring Framework 5.3 Reference, constructor injection guidance).

    3. C. It requires a reflection permission that is disabled by default

      Invents a nonexistent constraint: field injection needs no special reflection permission, so this is not why it is discouraged.

    4. D. It is significantly slower at runtime than constructor injection

      The concern is design quality, not speed; field injection is not meaningfully slower than constructor injection at runtime.

    Explanation

    Field injection is discouraged for design and maintainability reasons: it hides a class's real dependencies behind the container, cannot populate final/immutable fields, and forces reflection or a running context to construct the object for testing. The objection is about clarity and testability, not runtime performance, special permissions, or any incompatibility with stereotype-annotated classes.

  5. Question 5

    As of Spring 4.3+, when may @Autowired be omitted on a bean's constructor and the dependencies still be injected?

    1. A. When the class declares exactly one constructorCorrect answer

      Correct. Since Spring 4.3, a component that declares a single constructor has it used for injection implicitly, so @Autowired can be omitted (Spring Framework 5.3 Reference, single-constructor rule).

    2. B. Never — @Autowired is always mandatory on a constructor

      Incorrect. This contradicts the single-constructor feature introduced in Spring 4.3, under which the annotation is not required.

    3. C. Only for classes annotated @Configuration

      Incorrect. The rule applies to any component with a single constructor and is not restricted to @Configuration classes.

    4. D. Only when the constructor takes no arguments

      Incorrect. The rule depends on the constructor count being one, not on the number of arguments; a single constructor with parameters still qualifies.

    Explanation

    Since Spring 4.3, a component with a single constructor has that constructor used for dependency injection automatically, making @Autowired optional. The condition is that exactly one constructor is present, regardless of how many arguments it takes; when a class declares multiple constructors, one must be explicitly annotated to indicate which to use.

  6. Question 6

    In a Spring application, a class is annotated with `@Repository` instead of the generic `@Component`. Aside from being picked up by component scanning like any other stereotype, what additional benefit does `@Repository` provide?

    1. A. It registers the bean as a singleton, whereas `@Component` beans default to prototype scope.

      Confuses stereotype choice with scope. All stereotype annotations produce singleton-scoped beans by default; scope is controlled by `@Scope`, not by which stereotype is used.

    2. B. It makes the class eligible for automatic translation of persistence-technology exceptions into Spring's `DataAccessException` hierarchy.Correct answer

      Correct. The reference documentation states that `@Repository` marks a Data Access Object and that such classes are candidates for automatic exception translation when used with a `PersistenceExceptionTranslationPostProcessor` (Classpath Scanning and Managed Components).

    3. C. It causes Spring to generate a runtime implementation of the class's data access methods from their names.

      Confuses the core-framework `@Repository` stereotype with Spring Data's repository interface proxying. `@Repository` on its own only marks and registers a bean; it does not synthesize method implementations.

    4. D. It wraps every public method of the class in a transaction, so `@Transactional` is unnecessary on data access beans.

      Confuses the persistence stereotype with declarative transaction management. `@Repository` adds no transactional behaviour; transactions require `@Transactional` (or equivalent configuration).

    Explanation

    `@Component` is the generic stereotype for any Spring-managed component, while `@Service`, `@Controller`, and `@Repository` are specializations of it for more specific use cases. Beyond making a class a scan candidate, these specializations are appropriate targets for tooling, aspects, and additional framework processing — and `@Repository` in particular marks a class as a Data Access Object, making it a candidate for automatic persistence exception translation into Spring's consistent `DataAccessException` hierarchy. Stereotype choice does not change bean scope, which defaults to singleton for all of them; it does not generate method implementations, which is a Spring Data repository-interface feature rather than a core stereotype behaviour; and it adds no transactional semantics, which still require explicit declarative transaction configuration.

  7. Question 7

    When is a method annotated @PostConstruct invoked?

    1. A. Every time the bean is retrieved from the container

      Incorrect. @PostConstruct runs once during initialization, not on every retrieval of the bean; treating it as a per-lookup hook would be a misuse.

    2. B. Just before the container shuts down

      Incorrect. The pre-shutdown callback is @PreDestroy; @PostConstruct fires at initialization, not at teardown.

    3. C. Immediately after the constructor returns, before any dependency injection

      Incorrect. @PostConstruct runs after dependency injection completes, not before it, so injected collaborators are already available when it executes.

    4. D. After the bean is instantiated and its dependencies are injected, before it is put into serviceCorrect answer

      Correct. @PostConstruct runs once as part of bean initialization, after construction and dependency injection are complete, so the method can safely use injected collaborators (Spring Framework 5.3 Reference, @PostConstruct and @PreDestroy).

    Explanation

    @PostConstruct marks an initialization callback that Spring invokes exactly once, after the bean has been instantiated and all its dependencies injected but before it is placed into service. Because injection is already complete at that point, the method can rely on its injected collaborators. This is distinct from a per-retrieval hook and from the pre-shutdown callback, which is @PreDestroy.

  8. Question 8

    A class annotated @Component with no explicit name, EmailSender, is given which default bean name?

    1. A. A randomly generated identifier

      The default name is deterministic and derived from the class name, not random; a random identifier would make beans impossible to reference predictably by name.

    2. B. EmailSender (the simple class name unchanged)

      Close but misses the decapitalization step: the default generator lower-cases the first letter, so the name is not the class name left unchanged.

    3. C. emailSender (the simple class name with the first letter lower-cased)Correct answer

      Correct: component scanning derives the default bean name by decapitalizing the simple class name, so EmailSender becomes emailSender (Spring Framework 5.3 Reference, naming autodetected components).

    4. D. The fully-qualified class name

      The default uses only the simple class name, decapitalized; the package-qualified form is not used as the bean name.

    Explanation

    Component scanning generates a default bean name by taking the simple class name and lower-casing its first letter, so EmailSender is registered as emailSender. The package is not part of the name and the value is deterministic rather than random; an explicit name can still be supplied via @Component("name").

Practise all 18 Annotation-Based Configuration & Component Scanning questions

Spring Certified Professional (Develop) has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open Spring Certified Professional (Develop)

Other topics in this pack