Post contents:

In this series of posts I will give the answers I found for each of the Core Spring 4.2 Study Guide questions (you can download the guide at

Some background…

Suppose you have 2 teams working on two different layers of the application: web and database. Well we use the Spring container for wiring these layers together.

1What is dependency injection and what are the advantages?

Inversion of Control in containers like Spring do something similar like:

If you were to join a meeting and want to ask a question you have the control if you ask it. But if the speaker is asked by the organizers to ask questions at the end of the presentation than from our (the listeners) point of view we are dealing with inversion of control. That is: the speakers fulfills the lack of answers and clarifications on its own by asking us if we have any questions.

The bean that will have its dependencies added by the container is not allowed to call the injector service, so as Cosmina Iuliana said in her certification preparation book (this is called “Hollywood principle”):

Don’t call us, we’ll call you!

That’s the main principle of Inversion of Control.

Dependency Injection is a form of Inversion of Control used by containers like Spring to customize beans (the bean – as objects managed by Spring IoC container are called beans) or apply some given implementations on objects whose customizations are defined using interfaces. Techniques used for customizing the beans are constructor and setter injection – in that case you have to define a constructor that will accept certain implementation for the object field as a parameter. DI may be used by passing parameters to a factory method that is to create the “customized” object. So upon object creation DI ensures for “right” (in that very context) customization of the object.

From the advantages of dependency injection I want to mention:

  • Code is cleaner 
  • Code is more reusable – DI code becomes more generic and suitable for more implementations
  • Decoupling is more effective – less/or no direct dependencies are used the bean is less prone to be affected by changes in its dependencies
  • Classes become easier to test – interfaces or abstract classes are used for fields, one can use stubs or mocks implementations to be used while unit testing

2What is an interface and what are the advantages of making use of them in Java?

Interface is an abstract representation of a class. In Spring using an interface for some field in a class allows for automatic substituting with required specific implementation – this will be done by DI.

3What is meant by “application-context” and how do you create one?

Spring uses following types of containers for IoC over beans:

  1. BeansFactory – interface, a basic functionality container
  2. ApplicationContext – interface, a more advanced container that is a sub-interface of BeansFactory and adds enterprise-specific functionality to it.

There are numerous implementations of ApplicationContext interface and they differ in the way you supply the configuration metadata (info about how beans are to be made and configured/wired together).

For example we can initialize some ApplicationContext that uses XML as source for configuration metadata:

4What is the concept of a “container” and what is its lifecycle?

Spring container is an “environment” for the beans to live. The container creates, configures and wires beans together. Spring has many container implementations but actually you can divide them in 2 types:

  1. BeanFactory – a simple container with basic support for DI
  2. ApplicationContext – a more advanced container that has support for getting values from property files or sending events to different listeners.

Usually for developing ApplicationContext is used.

When an ApplicationContext is created several things happen:

  1. BeanDefinition creation
  2. Customizing BeanDefinitions by BeanFactoryPostProcessor
  3. Custom FactoryBeans creation
  4. BeanFactory instantiates beans instances
  5. Beans customization by BeanPostProcessor

Source: (in russian)

5Dependency injection using Java configuration

In Spring as of version 4 the way beans (Spring IoC container managed objects) are to be configured is defined in configuration metadata. Configuration metadata can be represented in 4 ways:

  1. XML
  2. Java annotations
  3. Java code
  4. Groovy configuration

For DI using Java configuration you have to use a JavaConfig class. It is annotated with @Configuration. Inside that class you declare some methods that return beans (configured instances of certain POJO classes that will be available in Spring context) and these methods should be annotated with @Bean

Here is an example:

Important to mention is the fact that the bean’s name in the context will be the same as method’s name and if you want a different name you will have to use the name attribute for the @Bean annotation.

For injecting one bean into another you just call the method that creates the bean and Spring intercepts the call so that the method returns the existing bean rather than running again:

Or alternatively set a parameter of some type that is already a bean to the method and everything will be autowired automatically:

For using this configuration class you have to use a suitable application context implementation. Usually you will use AnnotationConfigApplicationContext.

Application context may be instantiated without some specified configuration class and in that case you can supply it using .register() method.

Pay attention to the .refresh() method.

There are also some more things to mention about @Configuration classes. You can:

  • Use @Import for merging several @Configuration classes
  • Use @Autowire and @Value inside @Configuration classes as these classes are beans themselves 

Combining of XML and JavaConfig styles is possible in the following ways:

  • XML-centric way
  • JavaConfig centric way

The XML-centric way is done when you use mainly XML metadata and an XML-based application-config. For example you use ClassPathXmlApplicationContext. In this case you have to configure the XML metadata file so that it allows for using the @Configuration and @Autowired annotations in the JavaConfig classes that will be declared as beans. This is achieved by:

Because @Configuration annotation is meta-annotated (check this) with the @Component annotation any @Configuration class is a candidate for component scanning. So in essence that means that you can scan for the JavaConfig class if you provide the following line of code in your XML configuration:

@Configuration-centric combining of JavaConfig and XML:

For using XML metadata in a JavaConfig setup you have to use the @ImportResource annotation. You can use it after the @Configuration annotation. By this you are importing the XML definition to the config class.

6Dependency injection in XML, using constructor or setter injection

To start configuring DI using XML you have to create a XML metadata configuration file. Depending on the context implementation you will be using you can place that XML in different places. If you consider having that XML in the classpath you’ll have to use the ClassPathXmlApplicationContext, but if you want it to be somewhere in the filesystem than FileSystemXmlApplicaitonContext will be the right choice.

For an easy reference in case you use Maven place the XML file in the src/main/resources folder.

Spring has some special <beans> attributes that must be added to the XML for the context to run correctly:

Dependencies between beans in XML are declared either using constructor or setter passing of references. If a bean is declared in the XML and the POJO that corresponds to that bean has no custom constructor than the context will instantiate it using the default constructor.

Constructor injection is done in 2 ways:

  1. using <constructor-arg> element
  2. using c-namespace attributes (that requires adding some special configuration to the <beans> attributes):

<constructor-arg> matches with the order of the constructor arguments. If that is not the case and you want to mix the order of declaring <constructor-arg> elemtns, you have to supply the index number of the argument

Pay attention above – we set a constructor name not to a referenced bean but just to some custom value. There is also the possibility to set the constructor parameters by name but if the debug flag during compilation must be set to enabled for this option to work or in class you must place a @ConstructorProperties annotation at the constructor.

c-namespace allows for doing basically the same thing as with <constructor-arg> but in a little different way. c-namespace basically is all about declaring constructor arguments as attributes of the <bean> element.

First you write c: and that begins constructor parameter declaration, then if you know the name of the parameter you write it just after the (semicolon); and if that is a reference to another bean you add -ref – in the end you must obtain something like: c:parameterName-ref=”otherBeanName”. In case you want to use just the index number of the parameter just write something like c:_2-ref=”otherBeanName” (in this case 3rd parameter of the constructor shall be of type of OtherBean). And finally if there is only one parameter you just write c:_-ref=”otherBeanName” skipping index order number or name of the parameter.

Just as with constructor injection, there are 2 ways of using setter injection:

  1. using <property>
  2. using p-namespace

There may be some case when you need to pass a list of values to either a constructor or setter. In that case you have to use something like:

Or if you need to add a list of other beans:

You cannot wire collections using c-namespace or p-namespace. But, you can use an additional namespace – the util-namespace and in combination with c/p namespaces you will be able to pass collections for wiring.

And of course for using that you have to add one mode attribute to the beans element of your XML:

7Dependency injection using annotations (@Component, @Autowired)

@Component annotation is used to declare a class as a bean when you want the process of declaring beans to “search” (actually do a @ComponentScan) for classes in packages and configure them as beans. So, for the @Configuration to be able to scan for beans that have a @Component annotation you have to add a @ComponentScan to the @Configuration class. @Component will set the bean name derived from class name, but if you need to set the name explicitly you just need to supply it in the brackets like @Component(“beanName”).

In case you want to enable the component scanning functionality from XML you have to add <context:component-scan> element to the <beans> element in the XML configuration metadata file.

@ComponentScan looks for beans in the same package as the configuration class. There are 5 options for configuring the package to be scanned for components:

  1. @ComponentScan – scans current package
  2. @ComponentScan(“customPackage”) – scans package with name “customPackage”
  3. @ComponentScan(basePackages=”customPackage”) – same as above
  4. @ComponentScan(basePackages={“customPackage1″,”customPackage2”}) – scans these 2 packages
  5. @ComponentScan(basePackageClasses={Foo.class,Boo.class}) – will scan the packages that contain the 2 classes

@Autowired is used to indicate that at the place where it is added the Spring context must add a matching bean from the context. @Autowired can be used at constructors, methods and fields. This annotation will cause throwing of exceptions in 2 cases:

  1. No matching bean was found in the context
  2. 2 or more beans were found (ambiguity)

There are 2 interesting things about annotation-based context configuration:

  1. Spring allows for using @Named and @ManagedBean instead of @Component
  2. It also allows to use @Inject and @Resource instead of @Autowired

There are some subtle differences between Spring and Java annotations. 

8Component scanning, Stereotypes and Meta-Annotations

Check for component scanning in the answer above.

Spring allows marking your class as a bean ready for component-scanning using the following annotations:

  1. @Component – some piece of application that will be accessed “locally” (JAR, dll etc.) and will not be modified, although it can be extended and that way “modified”
  2. @Service – for beans that represent a service; basically the same thing as components except the fact that a service is usually accessed remotely (JMS, REST etc.)
  3. @Repository – for beans that represent a DAO
  4. @Controller – for beans that represent presentation layers

You can use in all the above cases the @Component annotation but using a specific annotation may be a better idea due to automatic translation of exceptions (in @Repository case) and future possible meanings in Spring.

Meta-annotations are annotations that annotate another annotation (ufff …)

For example, if you use the @Service annotation you automatically add the @Component annotation to your class because of the way @Service is declared:

If at the declaration some annotation is annotated with more than 1 annotation than you get a composed annotation. Meta-annotations can be also readily configured and will carry on that configuration each time you use the meta-annotated annotation.

9Scopes for Spring beans. What is the default?

Configuration metadata allows for defining 7 types of bean scopes. 5 of these scopes are available only if the ApplicaitonContext chosen implementation is web-aware, for example XmlWebApplicationContext or you’ll get an IllegalStateException meaning the selected scope is “unknown”. 

  1. singleton – the default scope for the beans. Will ensure that only one instance of the bean will be created per current IoC container (Spring container). Used for stateless beans.
  2. prototype – any number of bean instances may be created. Used for stateful beans. For this type of beans configured destruction lifecycle callbacks are not called. User must clean up this type of objects and release the resources that they are holding; usually using custom bean post-processor for that.
  3. request – a bean instance will be created per each HTTP request. @RequestScope may be used with @Component to assign this scope.
  4. session – one instance per HTTP Session lifecycle. @SessionScope may be used with @Component to assign this scope.
  5. globalSession – one instance per HTTP global Session. Usually only valid when used in a Portlet context
  6. application – one instance per ServletContext. @ApplicationScope may be used with @Component to assign this scope.
  7. websocket – one instance per WebSocket



If you use DispatcherServlet or DispatcherPortlet you’ll be able to use the 5 web-aware scopes without hassle; otherwise some additional initial setup is required (we won’t cover it here).

When working with scopes you may face a problem: from a singleton bean you may have a dependency on a prototype or any other type. For this type of wiring to work correct you have to use proxying. Proxying comes in 2 flavours:

  1. Class-based – is used when the dependency is defined by class and the referenced bean usually does not implement any interface. This type of proxying is achieved by <aop:scoped-proxy/> element in <bean> or by proxyMode=ScopedProxyMode.TARGET_CLASS attribute in @Scope annotation.
  2. Interface-based – is used when the dependency is defined by interface and the referenced bean implements at least one interface and all collaborators reference that bean by interface. This type of proxying is achieved by <aop:scoped-proxy proxy-target-class=”false”/> element in <bean> or by proxyMode=ScopedProxyMode.INTERFACES attribute in @Scope annotation.

10What is an initialization method and how is it declared in a Spring bean?

Initialization method is a method that does some initialization work after all the properties of the bean were set by the container.

It can be declared the following ways:

  • using XML init-method attribute for <bean>
  • using initMethod attribute of @Bean
  • using @PostConstruct annotation
  • implementing InitializingBean and overriding afterPropertiesSet method
  • in case there is a default-init-method attribute set for <beans> and the bean has a method whose name matches that attribute – it will be the initialization method, although this can be overridden using init-method in a specific <bean>  




… and one more way that is discouraged due to it coupling of code to Spring. You may implement InitializingBean interface and override afterPropertiesSet():

11What is a destroy method, how is it declared and when is it called?

Destroy method is the method that is called when the container containing it is destroyed (closed). The same way as with initialization method, here we have several ways (that mirror the init-method ways) to declare a destroy method:

  • XML destroy-method attribute of <bean>
  • @Bean destroyMethod attribute
  • @PreDestroy annotation 
  • implementation of DisposableBean and overriding of destroy() method
  • in case there is a default-destroy-method attribute set for <beans> and the bean has a method whose name matches that attribute – it will be the destroy method, although this can be overridden using destroy-method in a specific <bean>




… and one more way that is discouraged due to it coupling of code to Spring. You may implement DisposableBean interface and override destroy():

12What is a BeanFactoryPostProcessor and what is it used for?

BeanFactoryPostProcessor is an interface that allows for defining customizing BeanDefinitions for future beans before those beans are created.

The code above will change the class of bean foo to Boo.class.

Using BeanFactoryPostProcessor is useful when for example you want to populate class fields from a properties file. Actually Spring has some post-processors like: PropertyOverrideConfigurer (replaces @Value values with values from properties file, allows for default or no values) and PropertyPlaceholderConfigurer (same as previous except no default values can be given).

13What is a BeanPostProcessor and how is the difference to a BeanFactoryPostProcessor? What do they do? When are they called?

BeanPostProcessor interface is used for defining a bean that will adjust all beans at two distinct moments in time:

  • before init-method (by overriding postProcessBeforeInitialization())
  • after init-method (by overriding postProcessAfterInitialization())

More BeanPostProcessors may be defined and for ordering them you have to implement Ordered interface too.

BeanPostProcessor differs from BeanFactoryPostProcessor in the moment it is called. BeanFactoryPostProcessor is called before beans are initialized (works on BeanDefinitions) whilst BeanPostProcessor is called on existing beans. 

14Are beans lazily or eagerly instantiated by default? How do you alter this behavior?

Default beans scope is the singleton scope and for it the default instantiation type is the eager instantiation – that is at ApplicationContext startup. Propotype scoped beans are instantiated on each call to the bean so they are lazy by default. 

If you reference a lazy bean in a simple singleton bean than the referenced bean will be instantiated eagerly neglecting its custom lazy behaviour. 

Beans may be defined as lazily instantiable using:

  • the lazy-init attribute of the <bean> element or
  • using @Lazy for @Bean of @Component beans.

In case you want all singleton beans to be lazily instantiated:

  • in case of XML you shall use the default-lazy-init=”true” in the <beans> and
  • in case of @Configuration classe use @Lazy(value=true).

In a @Lazy @Configuration you may use @Lazy(value=false) over a @Bean in order to make it eagerly instantiable.

@Lazy doesn’t work as expected in case you have some beans extending an interface and one of those beans in annotated with @Primary. (there was such a bug but as of version 4.3.8 it’s not true anymore –

15What does component-scanning do?

Component scanning allows for scanning a certain package or set of packages for candidate beans; which in turn will be added automatically to the ApplicationContext without the developer to be required to declare them explicitly using @Bean in a @Configuration or in an XML configuration metadata file.

Component scanning is enabled by:

  1. annotating a @Configuration with @ComponentScan or
  2. <context:component-scan> in <beans>

By using @ComponentScan you are scanning the package that corresponds to the package of the current @Configuration. In case you need to specify a custom package or more packages you have to use:

please mention attribute name is basePackages

in even a crazier option: you may chose to scan packages that contain certain classes

In the xml version you just separate multiple package names by comma

16What is the behavior of the annotation @Autowired with regards to field injection, constructor injection and method injection?

@Autowired tries to find a matching bean by type and inject it at the place on annotation – that may be a constructor, a method (not only setter, but usually setter) and field.

In case no bean is found an exception will be thrown; to skip this you can set the required attribute of @Autowired to false, and in that case you have to pay attention to possible null values related exceptions.

In case of ambiguity there are 2 approaches:

  1. @Primary annotation to identify a “preferable” bean among different implementations of an interface
  2. @Qualifier annotation to indicate directly the preferred bean. (check further details in the next answer)

17How does the @Qualifier annotation complement the use of @Autowired?

@Qualifier allows for labeling beans. Meaning multiple beans can have the same qualifier and in case you are trying to autowire some collection of beans that match that qualifier all of those beans will be passed to the collection.

@Qualifier usually characterizes the bean rather than setting a direct name. For example you have some Meat and Milk beans than an appropriate qualifier for both of them would be @Qualifier(“food”)

foods field will contain 2 beans – meat and milk.

You can also create custom qualifiers like this:

now you can annotate your @Component with @SomeQualifier and at autowiring point use the same qualifier for autowiring the appropriate bean.

Or you can choose to create a qualifier with some parameter and filter beans not by qualifier only but additionally by that parameter

While autowiring parameterOne will be mandatory.

Although @Autowiring + @Qualifier combination is capable of identifying a bean by name it is a better approach to use @Resource when trying to inject by name.

18What is the role of the @PostConstruct and @PreDestroy annotations? When will they get called?

@PostConstruct annotation is used for identifying the init-method and @PreDestroy is used for the destroy-method. For these annotations to be available you must have the CommonAnnotationBeanPostProcessor registered in context. This bean is added to the context automatically if you set <context:annotation-config/> or <context:component-scan/> so if you need to use a custom CommonAnnotationBeanPostProcessor the default annotation configuration must be either turned off or removed (turn off by adding annotation-config=”false” to <context:component-scan/>). @ComponentScan enables CommonAnnotationBeanPostProcessor too.

@PostConstruct is called right after dependencies are injected but before bean is made available.

@PreDestroy is called before bean is removed from the container.

19What is a proxy object and what are the two different types of proxies Spring can create?

Proxy objects are objects that replace beans that should be injected in a singleton bean but are themselves lazily instantiable.

For example in a singleton bean you have a dependency on a session scoped bean. In this case at the container startup Spring will instantiate the singleton bean and during this process it will already need the bean that is session scoped. So here we have a problem.

So we can benefit from a proxy object that will mimic the bean that we actually need. But here comes another problem. Our dependency may be defined as an interface or as a class. So for each case one of the two types of proxies will be created:

  1. Interface proxy or
  2. Class proxy

Interface proxy is created by Spring itself whilst class proxy is generated by CGLib. 

So as usual we have the XML and the Java approach:


For target class proxy (the default):

For target interface proxy:


20What is the power of a proxy object and where are the disadvantages?

Proxies are a great means of adding functionality around beans methods. You can define some things to happen at different times around methods but you can also add new methods to beans by declaring new “parents” for the bean using @DeclareParents annotation.

Consider the image above. If Prox (the proxy) is the result of advising of B1 than you can write something like:

The code above will “extend” the original proxy so that now it will implement also the I2 interface.

It was tricky to find an answer to this question but finally I found this:

Here are some cons:

Dynamic proxying CGLib proxying
 – An additional dependency (only until Spring 3.2)
Proxying works only from outside … if internally you have method1() calling method2() than you cannot intercept the call to method2() since it’s not called from outside of the bean
Proxied object must be instantiated by Spring container, not by new keyword
Proxies are not serializable


21What are the limitations of these proxies (per type)?

Dynamic proxying CGLib proxying
Proxied class must implement interfaces Proxied class must provide a default constructor
  Final methods won’t allow for using CGLib proxying
  Resulting proxy is final (you cannot proxy a proxy)


22How do you inject scalar/literal values into Spring beans?

Depending on the beans wiring style you can use different methods to inject scalar/literal values:

  • for Java-based configurations: use @Value annotation at constructor arguments, over properties and at setter methods
  • for XML-based configurations: c-namespace for constructors and p-namespace for properties

23How are you going to create a new instance of an ApplicationContext?

ApplicationContext is just an interface so first you have to choose the implementation that best suits your needs.

All Known Implementing Classes:

AbstractApplicationContext, AbstractRefreshableApplicationContext, AbstractRefreshableConfigApplicationContext, AbstractRefreshablePortletApplicationContext, AbstractRefreshableWebApplicationContext, AbstractXmlApplicationContext, AnnotationConfigApplicationContext, AnnotationConfigWebApplicationContext, ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, GenericApplicationContext, GenericGroovyApplicationContext, GenericWebApplicationContext, GenericXmlApplicationContext, GroovyWebApplicationContext, ResourceAdapterApplicationContext, StaticApplicationContext, StaticPortletApplicationContext, StaticWebApplicationContext, XmlPortletApplicationContext, XmlWebApplicationContext

As seen above some require annotations and others XML.

In case of XML you just supply an Spring XML Configuration Metadata file; and in case of annotations you will need a configuration class annotated with @Configuration.

24What is a prefix?

As stated in the string you specify in the ApplicationContext constructor during initializaiton indicates the locaiton of configuration metadata – except the case you add a prefix to the string.

And from we have the following table:

Prefix Example Explanation
classpath: classpath:
Loaded from the classpath.
file: file:///data/config.xml Loaded as a URL, from the filesystem. [1]
http: http://myserver/logo.png Loaded as a URL.
(none) /data/config.xml Depends on the underlying ApplicationContext.

25What is the lifecycle on an ApplicationContext?

This question is basically answered above (see What is the concept of a “container” and what is its lifecycle?), but let’s list the lifecycle steps once again:

  1. BeanDefinition creation
  2. Customizing BeanDefinitions by BeanFactoryPostProcessor
  3. Custom FactoryBeans creation
  4. BeanFactory instantiates beans instances
  5. Beans customization by BeanPostProcessor

ApplicationContext can be closed in more ways:

  • through downcasting it to Closable and calling the close() method
  • using try-with-resources for implementations of AutoClosable

26What does the @Bean annotation do?

@Bean annotation is used on methods that will return beans of the specified return type. @Bean is usually used in configuration classes that don’t use components scan; but may be used as part of a component – that is a @Bean lite mode. In the later case inter-bean references are treated as standard Java method invocations – Spring doesn’t intercept the invocation (this applies only for inter-@Bean references in a non-@Configuration class).

27How are you going to create an ApplicationContext in an integration test or a JUnit test?

For automatic creation of an ApplicationContext for test purposes you will need the configuration class or XML configuration metadata file and 2 annotations.

28What do you have to do, if you would like to inject something into a private field?

From Spring point of view it doesn’t matter whether you use a private or a public field. 

For assigning a value to a field Spring uses either reflection or setter methods. For @Autowiring annotation you don’t need a setter whilst for c-namespace or p-namespace attributes of the <bean/> you will need some setter for the field (and it doesn’t matter whether the field is private or public).

29What are the advantages of JavaConfig? What are the limitations?

Biggest advantage of JavaConfig is type safety that is assured by IDEs. Another advantage is the possibility to use someone other’s classes. The limitation is that you cannot change the configuration dynamically – you have to rebuild the project.

30What is the default bean id if you only use “@Bean”?

In a configuration class the name of the bean in case you use @Bean on some method will instantiate a bean with the name matching the method name.

31Can you use @Bean together with @Profile?

@Profile can be used at 2 different levels:

  1. Configuration class level (all beans will be available only on profile being active) and
  2. Bean method level

32What is Spring Expression Language (SpEL for short)?

SpEL is an expression language that allows for querying and manipulating an object graph at runtime.

For example you may need to add the value from some bean field to another bean’s field:

33What is the environment abstraction in Spring?

Environment interface represents Spring abstraction for the environment. It deals with 2 aspects of a Spring application:

  1. profiles and
  2. properties from different sources (properties files, system and JVM properties etc.)

For a bean to interact with environment you can either make it EnvironmentAware or autowire the Environment.

34What can you reference using SpEL?

Using SpEL you can refference:

  • beans
  • system properties
  • system variables

35How do you configure a profile. What are possible use cases where they might be

You set the profile using @Profile annotation in Java based configurations and using profile attribute for <beans/> or <bean/>.

After defining the active beans for each profile you need to activate it. This can be done is several ways:

  • by calling .setActiveProfiles on context.getEnvironment()
  • setting system environment variable for
  • JVM system properties
  • servlet context parameters in web.xml
  • entry in JNDI

In integration tests:

  • using @ActiveProfiles

36How many profiles can you have?

Multiple profiles can be activated at once.

37How do you enable JSR-250 annotations like @PostConstruct?

For these annotation to be available you must have the CommonAnnotationBeanPostProcessor registered in context. This bean is added to the context automatically if you set <context:annotation-config/> or <context:component-scan/> so if you need to use a custom CommonAnnotationBeanPostProcessor the default annotation configuration must be either turned off or removed (turn off by adding annotation-config=”false” to <context:component-scan/>).

38Why are you not allowed to annotate a final class with @Configuration

Spring requires for subclassing classes annotated with @Configuration (for example to check if a bean exists before calling for it’s creation once again) and for that it uses CGLib proxying so if we remember the requirements for proxying a class using CGLib – you cannot make a proxy of a final class.

39Why must you have a default constructor in your @Configuration annotated class?

You must have a default constructor because Spring looks for it when using CGLib proxying. And that is a Spring limitation not a CGLib one.

40Why are you not allowed to annotate final methods with @Bean?

Once again – the reason for not allowing final methods to be annotated with @Bean is that Spring makes CGLib proxies for @Configuration classes.

41What is the preferred way to close an application context?

It depends on the web-awareness of the application context. If you have to do with a web-aware application context than it will be automatically closed by the ContextLoaderListener using the close() method.

In a non-web environment you have to register a shutdown hook on context and on JVM closing the application context will be closed too.

42How can you create a shared application context in a JUnit test?

Spring automatically caches the application context for usage in a test suite (here referring all tests that are run in a JVM from same Maven build) in case the locations (for XML) or classes (for @Configuration-annotated classes) attribute of @ContextConfiguration coincide across different test classes.

43What does a static @Bean method do?

When defining a method that returns a bean of BeanFactoryPostProcessor type it is best to declare it as static because of the fact that this type of beans require very early initialization and thus the must not be affected by @Autowire, @PostConstruct and @Value annotations from a @Configuration annotated class. The static method declaration will avoid requirement to have the declaring class to be instantiated.

44What is a ProperySourcesPlaceholderConfigurer used for? (this is a question from Core Spring 4.2-4.3 Certification Study Guide)

45What is a namespace used for in XML configuration (this is a question from Core Spring 4.2-4.3 Certification Study Guide)

46If you saw one of the <context/> elements covered in the course, would you know what it does? (this is a question from Core Spring 4.2-4.3 Certification Study Guide)

47What is a ProperyPlaceholderConfigurer used for?

This bean is used for defining the location of the properties file to be used in assigning values to bean properties. But it also allows for searching the required value in the system and/or environment variables.

48What is @Value used for?

This annotation is used for assigning some value to a bean field. It can be used at different levels:

  • constructor
  • setter
  • field

It is not accessible in a BeanFactoryPostProcessor and BeanPostProcessor by the time it is applied using a BeanPostProcessor.

49What is the difference between $ and # in @Value expressions?

For property placeholders we use $ whilst for SpEL we use #

for using @Value with ${…} you will need to have a @PropertySources annotation added to the configuration class so that it will know where to look for the properties file.


  1. Hello Man,

    I’m preparing the Spring 4.2 Certification Exam and I found your blog.

    I want to say that it’s just wonderfull ! Really Many Thanks Man !


  2. Where do I find the answers marked as “(this is a question from Core Spring 4.2-4.3 Certification Study Guide)” ?


Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.