Spring Certification Notes
Spring Certification Notes
Spring Certification Notes
What is an interface and what are the advantages of making use of them in Java? ......... 4
How are you going to create an ApplicationContext in an integration test test? .............. 9
What is the preferred way to close an application context? Does Spring Boot do this for
you? ......................................................................................................................................... 10
Web Application................................................................................................................. 11
Are beans lazily or eagerly instantiated by default? How do you alter this behaviour?. 15
Consider how you enable JSR-250 annotations like @PostConstruct and @PreDestroy?
When/how will they get called? ............................................................................................ 23
What is the behavior of the annotation @Autowired with regards to field injection,
constructor injection and method injection? ....................................................................... 23
What do you have to do, if you would like to inject something into a private field? ....... 26
How does the @Qualifier annotation complement the use of @Autowired? ................... 27
What is a proxy object and what are the two different types of proxies Spring can
create? ..................................................................................................................................... 27
What is the power of a proxy object and where are the disadvantages? .......................... 28
What are the advantages of Java Config? What are the limitations? .............................. 29
What is the default bean id if you only use @Bean? How can you override this? ........... 30
Why are you not allowed to annotate a final class with @Configuration? ...................... 30
How do you configure profiles? What are possible use cases where they might be
useful? ..................................................................................................................................... 30
Collections ........................................................................................................................... 34
Where can properties in the environment come from – there are many sources for
properties – check the documentation if not sure. Spring Boot adds even more. ............ 35
What is an anti-pattern?
An anti-pattern is a commonly used template that attempts to solve a type of problem but turns
out to be counterproductive and inefficient. An anti-pattern may also be a habit among software
developers that reduces productivity or some desirable code quality etc.
Examples: premature optimization, analysis paralysis.
Meta-Annotations
A meta-annotation is simply an annotation that can be applied to another annotation. Meta-
annotations can also be combined to create composed annotations. For example, the
@RestController annotation from Spring MVC is composed of @Controller and
@ResponseBody.
Scopes for Spring beans? What is the default scope?
Scope Description
Singleton (Default) Scopes a single bean definition to
a single object instance per Spring IoC
container.
Prototype Scopes a single bean definition to any
number of object instances.
Request Scopes a single bean definition to the
lifecycle of a single HTTP request; that is,
each HTTP request has its own instance of a
bean created off the back of a single bean
definition. Only valid in
WebApplicationContext
Session Scopes a single bean definition to the
lifecycle of an HTTP Session. Only valid in
WebApplicationContext
Application Scopes a single bean definition to the
lifecycle of a ServletContext. Only valid in
WebApplicationContext
Websocket Scopes a single bean definition to the
lifecycle of a WebSocket. Only valid in
WebApplicationContext
When you use singleton-scoped beans with dependencies on prototype beans, be aware that
dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-
scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then
dependency-injected into the singleton bean. The prototype instance is the sole instance that is
ever supplied to the singleton-scoped bean.
Are beans lazily or eagerly instantiated by default? How do you alter
this behaviour?
Singleton Spring beans in an application context are eagerly initialized by default, as the
application context is created.
An instance of a prototype scoped bean is typically created lazily when requested.
To explicitly set whether beans are to be lazily or eagerly initialized, the @Lazy annotation
can be applied either to:
- Methods annotated with the @Bean annotation. Bean will be lazy or not as specified
by the boolean parameter to the @Lazy annotation (default value is true).
- Classes annotated with the @Configuration annotation. All beans declared in the
configuration class will be lazy or not as specified by the boolean parameter to the
@Lazy annotation (default value is true).
- Classes annotated with @Component or any related stereotype annotation. The bean
created from the component class will be lazy or not as specified by the boolean
parameter to the @Lazy annotation (default value is true).
As you can see in the preceding diagram, the initialization phase is divided into these two steps:
- Load bean definitions. Create an ordered graph
- Instantiate and run BeanFactoryPostProcessors (you can update bean definitions here).
- Initialize bean instances
Load bean definitions
In this step, all the configuration files – @Configuration classes or XML files – are processed.
For Annotation-based configuration, all the classes annotated with @Components are
scanned to load the bean definitions.
Spring provides multiple BeanFactoryPostProcessor beans, so, it is invoked to resolve
runtime dependencies such as reading values from external property files. In a Spring
application, BeanFactoryPostProcessor can modify the definition of any bean.
To influence the order in which bean factory post processors are invoked, their bean definition
methods may be annotated with the @Order annotation. If you are implementing your own
bean factory post processor, the implementation class can also implement the Ordered
interface.
BeanFactory object is passed as an argument to the postProcess() method of
BeanFactoryPostProcessor. Let's see how BeanFactoryPostProcessor works, and how to
override it in our application:
- BeanFactoryPostProcessor works on the bean definitions or the configuration
metadata of the bean before the beans are actually created.
- Spring provides several useful implementations of BeanFactoryPostProcessor, such
as reading properties and registering a custom scope.
- You can write your own implementation of the BeanFactoryPostProcessor interface.
- If you define a BeanFactoryPostProcessor in one container, it will only be applied to
the bean definitions in that container.
Example:
Here, we'll use the DataSource bean to be configured with the database values such as
username, password, db url, and driver. So, in the preceding code, how do we resolve the
@Value and ${..} variables? We need a PropertySourcesPlaceholderConfigurer to evaluate
them. This is a BeanFactoryPostProcessor.
Why would you define a static @Bean method?
Special consideration must be taken for @Bean methods that return Spring
BeanFactoryPostProcessor (BFPP) types. Because BFPP objects must be instantiated very
early in the container lifecycle, they can interfere with processing of annotations such as
@Autowired, @Value, and @PostConstruct within @Configuration classes. To avoid these
lifecycle issues, mark BFPP-returning @Bean methods as static. For example:
By marking this method as static, it can be invoked without causing instantiation of its
declaring @Configuration class, thus avoiding the above-mentioned lifecycle conflicts. Note
however that static @Bean methods will not be enhanced for scoping and AOP semantics as
mentioned above. This works out in BFPP cases, as they are not typically referenced by other
@Bean methods.
Order of initialization
What is a destroy method, how is it declared and when is it called?
A destroy method is a method in a Spring bean that will be invoked by the Spring application
container immediately before the bean is to be taken out of use, typically when the Spring
application context is about to be closed.
When defining a Spring bean using Java configuration, methods named close and
shutdown will automatically be registered as destruction callback methods by the Spring
application container, as if these methods had been specified using the destroyMethod element
of the @Bean annotation. To avoid this, set the destroyMethod element of the @Bean
annotation to the empty string, like in this example:
Note: Only invoked on beans whose lifecycle is under the full control of the factory, which
is always the case for singletons but not guaranteed for any other scope.
Object has a public setter methods that takes dependent classes as method arguments to inject
dependencies. For setter-based dependency injection, the constructor of the dependent class is
not required.
Advantages of setter injection:
- It is more readable than the constructor injection
- It solves the circular dependency problem in the application
- It allows costly resources or services to be created as late as possible, and only when
required
- It does not require the constructor to be changed, but dependencies are passed through
public properties that are exposed
Disadvantage of the setter injection:
- Security is lesser in the setter injection pattern, because it can be overridden
- A setter-based dependency injection does not provide a code structure as compact as
the constructor injection
What is the behaviour of the annotation @Autowired?
Autowiring is a mechanism which enables more or less automatic dependency resolution
primarily based on types. The basic procedure of dependency injection with the @Autowired
is:
- The Spring container examines the type of the field or parameter that is to be
dependency injected.
- The Spring container searches the application context for a bean which type matches
the type of the field or parameter.
- If there are multiple matching bean candidates and one of them is annotated with
@Primary, then this bean is selected and injected into the field or parameter.
- If there are multiple matching bean candidates and the field or parameter is annotated
with the @Qualifier annotation, then the Spring container will attempt to use the
information from the @Qualifier annotation to select a bean to inject.
- If there is no other resolution mechanism, such as the @Primary or @Qualifier
annotations, and there are multiple matching beans, the Spring container will try to
resolve the appropriate bean by trying to match the bean name to the name of the field
or parameter. This is the default bean resolution mechanism used when autowiring
dependencies.
- If still no unique match for the field or parameter can be determined, an exception will
be thrown.
The following are common for all the different use-cases of the @Autowired annotation:
- Dependency injection, regardless of whether on fields, constructors or methods, is
performed by the AutowiredAnnotationBeanPostProcessor. Due to this, the
@Autowired annotation cannot be used in neither BeanPostProcessor-s nor in
BeanFactoryPostProcessor-s.
- All dependencies annotated with @Autowired are required as default and an exception
will be thrown if such a dependency cannot be resolved.
- If the type that is autowired is an array-type, then the Spring container will collect all
beans matching the value-type of the array in an array and inject the array.
- If the type that is autowired is a collection type, then the Spring container will collect
all beans matching the collection’s value-type in a collection of the specified type and
inject the collection.
- If the type that is autowired is a Map, then as long as the expected key type is String
Map values will contain all beans of the expected type, and the keys will contain the
corresponding bean names.
What do you have to do, if you would like to inject something into a
private field?
You can use:
- Constructor
- Setter
- Mark @Autowired on field
- Use @Value
What is a proxy object and what are the two different types of proxies
Spring can create?
A proxy object is an object that have the same methods, at least the public methods, as the
object it proxies. The purpose of this is to make the proxy indistinguishable from the object it
proxies.
- JDK Proxy: This is also known as a dynamic proxy. Its API is built into the JDK. For
this proxy, the Java interface is required
- CGLib Proxy: This is NOT built into JDK. However, it is included in Spring JARS,
and is used when the interface is not available. It cannot be applied to final classes or
methods
What are the limitations of these proxies (per type)?
Limitations of JDK Dynamic Proxies
- Requires the proxied object to implement at least one interface.
- Only methods found in the implemented interface(s) will be available in the proxy
object.
- Proxy objects must be referenced using an interface type and cannot be referenced using
a type of a superclass of the proxied object type. This unless of course the superclass
implements interface(s) in question.
- Does not support self-invocations. Self-invocation is where one method of the object
invokes another method on the same object.
Limitations of CGLIB Proxies
- Requires the class of the proxied object to be non-final. Subclasses cannot be created
from final classes.
- Requires methods in the proxied object to be non-final. Final methods cannot be
overridden.
- Does not support self-invocations. Self-invocation is where one method of the object
invokes another method on the same object.
- Requires a third-party library. Not built into the Java language and thus require a
library. The CGLIB library has been included into Spring, so when using the Spring
framework, no additional library is required.
What is the power of a proxy object and where are the disadvantages?
Powers of proxy objects are:
- Can add behaviour to existing beans. Examples of such behaviour: Transaction
management, logging, security.
- Makes it possible to separate concerns such as logging, security etc from business logic.
Disadvantages of proxy objects are:
- It may not be obvious where a method invocation is handled when proxy objects are
used
- A proxy object may chose not to invoke the proxied object
- If multiple layers of proxy objects are used, developers may need to take into account
the order in which the proxies are applied
- Proxy object may incur overhead
- Only methods with public visibility will be advised
- Local or internal method calls within an advised class doesn’t get intercepted by
proxy, so advise method of the aspect does not get fired/invoked
What are the advantages of Java Config? What are the limitations?
Advantages of Spring Java configuration, configuration classes annotated with
@Configuration, over Spring XML configuration and/or annotation-based configuration in
Spring bean classes with component scanning:
- Regular Java refactoring tooling will work on Java configuration classes. Special
tooling needed for Spring XML configuration files.
- Type-checking performed by Java compiler and IDE.
- Can be located in one or a few places, compared to annotation-based configuration that
is more spread out.
- Combining Spring Java configuration, JUnit and Mockito you can write flexible
integration tests mocking only some Spring Beans.
Limitations of Spring Java configuration:
- Configuration classes cannot be final. Configuration classes are subclassed by the
Spring container using CGLIB and final classes cannot be subclassed.
@Bean methods may also be declared within classes that are not annotated with
@Configuration. For example, bean methods may be declared in a @Component class or
even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite'
mode. In contrast to the semantics for bean methods in @Configuration classes, 'inter-bean
references' are not supported in lite mode. Instead, when one @Bean-method invokes
another @Bean-method in lite mode, the invocation is a standard Java method
invocation. Spring does not intercept the invocation via a CGLIB proxy. This is analogous to
inter-@Transactional method calls where in proxy mode, Spring does not intercept the
invocation.
What is the default bean id if you only use @Bean? How can you
override this?
Default bean’s id is method’s name. To override it, use @Bean(name=”name”) or
@Bean(“name”).
How do you configure profiles? What are possible use cases where
they might be useful?
In Java configuration, you can use the @Profile annotation to specify which profile a bean
belongs to. The @Profile annotation may be used in any of the following ways:
- At class level in @Configuration classes. Beans in the configuration class and beans
in configuration(s) imported with @Import annotation(s).
- At class level in classes annotated with @Component or annotated with any other
annotation that in turn is annotated with @Component.
- On methods annotated with the @Bean annotation. Applied to a single method
annotated with the @Bean annotations.
- Type level in custom annotations. Acts as a meta-annotation when creating custom
annotations.
Spring honors two separate properties when determining which profiles are active:
spring.profiles.active and spring.profiles.default:
- If spring.profiles.active is set, then its value determines which profiles are active.
- If spring.profiles.active isn’t set, then Spring looks to spring.profiles.default.
- If neither spring.profiles.active nor spring.profiles.default is set, then there are no active
profiles, and only those beans that aren’t defined as being in a profile are created.
Note! You can activate multiple profiles at the same time by listing the profile names, separated
by commas.
If you would like to define alternative beans with different profile conditions, use distinct
Java method names pointing to the same bean name via the @Bean name attribute, as
indicated in the example above.
Note! Profile names in the @Profile annotation can be prefixed with !, indicating that the beans
are to be registered when the profile with specified name is not active.
The beans in the above configuration class will be registered if any profile except the “prod”
A default value can be specified if the property value to be injected is not available.
To set a default value for primitive types such as boolean and int, we use the literal value:
Types in expressions
T(java.lang.Math)
T(java.lang.Math).PI
T(java.lang.Math).random()
#{2 * T(java.lang.Math).PI * circle.radius}
#{disc.title + ' by ' + disc.artist}
#{counter.total == 100}
#{scoreboard.score > 1000 ? "Winner!" : "Loser"}
#{disc.title ?: 'Rattle and Hum'} If disc.title is null, then the expression evaluates to “Rattle and
Hum”.
Regular expressions
#{admin.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.com'}
Collections
#{jukebox.songs[4].title}
#{jukebox.songs[T(java.lang.Math).random() * jukebox.songs.size()].title}
#{jukebox.songs.?[artist eq 'Aerosmith']} Suppose you want a list of all songs in the jukebox
where the artist property is Aerosmith.
Notice that the Environment object is @Autowired into the configuration class.
Where can properties in the environment come from – there are many
sources for properties – check the documentation if not sure. Spring
Boot adds even more.
Spring Boot uses a very particular PropertySource order that is designed to allow sensible
overriding of values. Properties are considered in the following order:
1. Devtools global settings properties on your home directory (~/.spring-boot-
devtools.properties when devtools is active).
2. @TestPropertySource annotations on your tests.
3. @SpringBootTest#properties annotation attribute on your tests.
4. Command line arguments.
5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an
environment variable or system property).
6. ServletConfig init parameters.
7. ServletContext init parameters.
8. JNDI attributes from java:comp/env.
9. Java System properties (System.getProperties()).
10. OS environment variables.
11. A RandomValuePropertySource that has properties only in random.*.
12. Profile-specific application properties outside of your packaged jar (application-
{profile}.properties and YAML variants).
13. Profile-specific application properties packaged inside your jar (application-
{profile}.properties and YAML variants).
14. Application properties outside of your packaged jar (application.properties and YAML
variants).
15. Application properties packaged inside your jar (application.properties and YAML
variants).
16. @PropertySource annotations on your @Configuration classes.
17. Default properties (specified by setting SpringApplication.setDefaultProperties).