Java Configuration & the Application Context practice questions

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

Java Configuration & the Application Context practice questions from Spring Certified Professional (Develop) (2V0-72.22). This pack has 26 questions tagged Java Configuration & the Application Context, 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 Java Configuration & the Application Context

  1. Question 1

    Two beans of type PaymentService are defined. What happens when application code calls context.getBean(PaymentService.class)?

    1. A. It returns whichever bean was defined first

      Spring does not silently pick the first-defined candidate; an ambiguous single-type lookup is treated as an error, not resolved by definition order.

    2. B. It throws NoUniqueBeanDefinitionException unless one candidate is marked @PrimaryCorrect answer

      When multiple candidates match a single-type lookup the resolution is ambiguous, so the container throws NoUniqueBeanDefinitionException; marking one candidate @Primary (or selecting by name/qualifier) disambiguates it (Spring Framework 5.3 Reference — Autowiring & @Primary).

    3. C. It returns a List containing both beans

      A single-type getBean call is expected to return one instance, not collapse multiple matches into a List; retrieving all matches is a different, collection-style lookup.

    4. D. It returns null because the lookup is ambiguous

      Spring signals the ambiguity by throwing an exception rather than quietly returning null.

    Explanation

    Requesting a single bean by type when more than one candidate matches is ambiguous, and Spring surfaces that ambiguity by throwing NoUniqueBeanDefinitionException rather than guessing. Designating one candidate as primary, or selecting by name or qualifier, tells the container which one to return. It does not default to the first definition, hand back null, or bundle the matches into a collection for a single-type request.

  2. Question 2

    An ApplicationContext holds two beans of type DataSource, registered as 'primary' and 'replica'. Which single call returns the 'replica' bean already typed as DataSource, with no cast required?

    1. A. context.getBean(DataSource.class)

      With two DataSource candidates a by-type lookup is ambiguous and throws NoUniqueBeanDefinitionException; it cannot select 'replica'.

    2. B. context.getBean("replica")

      The name-only overload returns Object, so the caller would have to cast it to DataSource; it does not satisfy the 'no cast' requirement.

    3. C. context.getBeanNamesForType(DataSource.class)

      This returns an array of matching bean names (Strings), not the DataSource instance, so a further lookup by name is still needed.

    4. D. context.getBean("replica", DataSource.class)Correct answer

      The name-plus-type overload selects the bean by its id and returns it already typed, so it unambiguously yields the 'replica' DataSource without a cast (Spring Framework 5.3 Reference — retrieving beans by name and type).

    Explanation

    The overload taking both a bean name and a required type selects the specific bean by id and returns it as that type, which resolves the ambiguity of two DataSource beans and needs no cast. The by-type-only call is ambiguous here, the name-only call returns Object (requiring a cast), and getBeanNamesForType returns names rather than the instance.

  3. Question 3

    A team has three `@Configuration` classes in the package `com.example.app.config` and several `@Service` and `@Repository` classes elsewhere under `com.example.app`. They bootstrap the container with `@ComponentScan("com.example.app")` on a single root configuration class. Which statement best describes how the `@Configuration` classes under the scanned package are treated?

    1. A. They are ignored by component scanning; only classes listed in an `@Import` are ever processed as configuration.

      Assumes `@Import` is the only route to registering a configuration class. `@Import` is one way to compose configuration explicitly, but it is not required — scanning is an equally valid discovery mechanism.

    2. B. They are picked up as candidate components, because `@Configuration` is itself meta-annotated with `@Component`, and their `@Bean` methods are then processed.Correct answer

      `@Configuration` is meta-annotated with `@Component`, so a configuration class in a scanned package is a scan candidate like any other stereotype; once registered, its `@Bean` methods are processed to contribute bean definitions.

    3. C. They are registered as plain beans, but their `@Bean` methods are skipped unless the class is also explicitly imported.

      Confuses registration with `@Bean` processing. Once a `@Configuration` class is a bean definition in the context — however it got there — its `@Bean` methods are processed; an extra `@Import` is not a precondition.

    4. D. Component scanning rejects them and startup fails, because a class may not be both a scan candidate and a configuration class.

      Invents a conflict that does not exist. Being a scan candidate and being a configuration class are complementary, not mutually exclusive; nothing about the combination is an error.

    Explanation

    Because the `@Configuration` annotation is itself meta-annotated with `@Component`, configuration classes are ordinary component-scan candidates: a scan over their package registers them, and the configuration-class post-processing then reads their `@Bean` methods to add those bean definitions. This means split configuration can be assembled either by scanning a common package or by explicit composition, so treating explicit import as the sole mechanism is wrong; likewise, registration is what triggers `@Bean` processing, so no additional import is needed to activate the bean methods; and there is no rule that makes a class both scannable and configuration-bearing an error.

  4. Question 4

    How do you bring legacy XML-defined bean definitions into an otherwise Java-config application?

    1. A. Add @ImportResource("classpath:legacy-beans.xml") to a @Configuration classCorrect answer

      @ImportResource("classpath:legacy-beans.xml") on a @Configuration class loads XML bean-definition resources into the Java-config context, the standard bridge between the two styles (Spring Framework 5.3 Reference — Combining Java and XML with @ImportResource).

    2. B. Use @ComponentScan, which also reads XML files

      @ComponentScan discovers annotated component classes on the classpath; it does not read XML bean-definition files.

    3. C. XML and Java configuration cannot be mixed

      XML and Java configuration can be freely combined, so the claim that they cannot be mixed is false.

    4. D. Use @Import(LegacyBeans.xml.class)

      @Import brings in @Configuration or component classes, not XML files, and there is no LegacyBeans.xml.class type to reference.

    Explanation

    Legacy XML bean definitions are pulled into a Java-config context with the annotation that loads external XML resources onto a @Configuration class, which is the standard bridge between the two configuration styles. Mixing XML and annotation-based configuration is fully supported.

  5. Question 5

    What is required to inject a request-scoped bean into a singleton bean so it resolves correctly per request?

    1. A. A scoped proxy (e.g. @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)), so the singleton holds a proxy that delegates to the current request's instanceCorrect answer

      A scoped proxy such as @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS) injects a proxy into the singleton that delegates every call to the instance bound to the currently active request (Spring Framework 5.3 Reference — Scoped beans as dependencies).

    2. B. Annotating the field @Lazy, which alone makes it request-aware

      @Lazy only defers creation of the injected bean; on its own it does not make the reference resolve per request.

    3. C. Nothing special — a direct injection works correctly per request

      A plain direct injection does not silently reuse one stale instance — because the singleton is created before any request is bound, Spring cannot resolve the request-scoped dependency and fails (e.g. "Scope 'request' is not active for the current thread" / "No thread-bound request found"). A scoped proxy is required to defer resolution to each request.

    4. D. Making the singleton itself prototype-scoped

      Making the singleton prototype-scoped changes the outer bean's lifecycle rather than solving per-request resolution, defeating the purpose.

    Explanation

    Because a singleton is instantiated only once, it cannot directly hold a shorter-lived request-scoped bean; instead a scoped proxy is injected that dispatches each call to the instance bound to the currently active request. This delegation is what keeps the reference correct across many requests over the singleton's lifetime.

  6. Question 6

    You have two separate classes, AppConfig and DataConfig, each annotated @Configuration. You register only AppConfig with the context. Which TWO of the following would also make DataConfig's bean definitions available in the container? Select TWO.

    1. A. Nothing is needed — the container always discovers every @Configuration class on the classpath

      The container only processes configuration you explicitly register, import, or that component scanning discovers; it does not automatically pick up every @Configuration class on the classpath, so DataConfig would stay unregistered.

    2. B. Nothing is needed — @Configuration classes in the same package are merged automatically

      Sharing a package has no aggregating effect; @Configuration classes are not merged by virtue of being in the same package, so DataConfig's beans remain unavailable.

    3. C. Make AppConfig extend DataConfig so its @Bean methods are inheritedCorrect answer

      Spring's configuration parser walks the superclass hierarchy, so extending DataConfig causes its inherited @Bean methods to be processed and AppConfig contributes DataConfig's bean definitions. It genuinely works, though it is the less-preferred, non-idiomatic option.

    4. D. Annotate AppConfig with @Import(DataConfig.class)Correct answer

      @Import pulls another @Configuration class's bean definitions into the importing configuration, the idiomatic way to compose separate Java configurations and make DataConfig's beans available (Spring Framework 5.3 Reference — Composing Java-based Configurations).

    Explanation

    Only configuration that is explicitly registered, imported, or found by component scanning is processed, so DataConfig is not picked up merely by sitting on the classpath or in the same package as AppConfig. Importing DataConfig into AppConfig pulls its bean definitions into the registered configuration, and having AppConfig extend DataConfig also works because the configuration parser processes inherited @Bean methods from the superclass. Importing is the idiomatic mechanism while inheritance is a legitimate but discouraged alternative.

  7. Question 7

    By default, what name is given to a bean defined by a @Bean method?

    1. A. A randomly generated UUID

      Incorrect: bean ids are not randomly generated UUIDs.

    2. B. The simple name of the bean's return type

      Incorrect: the simple name of the return type is not used as the default bean id for a @Bean method.

    3. C. The name of the @Bean methodCorrect answer

      Correct: unless overridden with @Bean(name=...), the bean's id is the name of the @Bean method.

    4. D. The fully-qualified class name of the return type

      Incorrect: the fully-qualified class name of the return type is not used as the default id.

    Explanation

    A @Bean method's default bean id is taken from the method name itself, unless it is overridden through the annotation's name attribute. Neither the return type's name nor a generated identifier is used as the default.

  8. Question 8

    An application has several explicit @Configuration classes plus many @Service and @Repository classes spread across packages. On a single root configuration class, which combination pulls in both the explicit configurations and the stereotype-annotated beans while keeping consistent singleton semantics across the merged container?

    1. A. @ImportResource for the configuration classes and a @Bean method for each stereotype class.

      @ImportResource loads XML, not @Configuration classes, and hand-writing a @Bean method per component defeats the purpose of stereotype scanning; this is not the intended composition.

    2. B. @Import(...) for the explicit @Configuration classes plus @ComponentScan for the stereotype-annotated beans.Correct answer

      @Import composes explicit configurations and @ComponentScan discovers stereotype components; combining them on one root class merges the whole graph with consistent singleton semantics (Spring Framework 5.3 Reference — composing configurations).

    3. C. @ComponentScan alone, since it also processes any @Import targets automatically.

      @ComponentScan detects stereotype components but does not process @Import declarations for you; explicit configurations still need @Import (or to be found by scanning) to be registered.

    4. D. Have the root class extend every other @Configuration class so all their @Bean methods are inherited.

      Inheritance can pull in a superclass's @Bean methods but is limited to a single superclass and is the discouraged, non-idiomatic route; it also does nothing to discover the scattered stereotype beans.

    Explanation

    Combining @Import for the explicit @Configuration classes with @ComponentScan for the stereotype-annotated beans is the idiomatic way to assemble a modular configuration on one root class, and the merged container keeps consistent singleton semantics. @ComponentScan alone will not process @Import targets, @ImportResource is for XML, and single-superclass inheritance is a discouraged partial solution that misses the scanned components.

Practise all 26 Java Configuration & the Application Context 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