Spring Interview Module 1 Container, Dependency, and IoC Flashcards
what is loose coupling?
- tight coupling: require tightly coupled dependency to function. if the dependency changes, then the function need difficult refactoring
- loose coupling: instead of hard code the dependency, dependency is not directly coupled but loosely defined. the actual dependency can be flexibly determined later
e.g. autowire service in controller, the exact implementation of service dependency can be created separately
what is a dependency?
another class depends on to provide its service
what is IOC inversion of control?
normal way for a parent class to have a dependency, dependency is hardcoded and instantiated by the parent class
IOC allows spring to manage the instantiation and injection of dependency bean into parent class instead
what is dependency injection?
spring framework search for the dependency bean, instantiate the bean, and wire the bean into dependent class for us. instead of we hardcode the dependency when instantiate a new bean by constructing
e.g. @Autowired
what is auto wiring?
process of spring searching for the dependency bean and instantiate beans and wire dependencies
what are the important roles of an IOC container?
- find / identify beans
- wire dependencies : instantiate and inject the dependencies
- manage lifecycle of the bean: instantiate, process bean lifecycle events, destroy bean after complete use
what are bean factory and application context?
can you compare bean factory with application context?
bean factory is basic version. like IOC container
application context: IOC container features
- spring AOP features
- I18N capabilities
- WebApplicationContext for web applications etc
most of time, spring recommends using application context. only in servere memory constraints, bean factory is used
how do you create an application context with spring?
- XML + ApplicationContext context = new ClassPathXmlApplicatonContext(new String[] {“BusinessApplicationContext.xml”})
- JAVA @Configuration + ApplicationContext context = new AnnotationConfigApplciationContext(SpringContext.class)
- create in unit test : @RunWith(SpringJunit4ClassRunner.class) @ContextConfiguration()
how does spring know where to search for components or beans?
what is a component scan?
scanning all packages can cause performance issues
search spring does to find components. input is given by coder
how do you define a component scan in XML ans JAVA configurations?
scan range can be defined by XML or by @ComponentScan
how is component scan done with spirng boot?
@SpringBootApplication or @SpringBootTest
auto initiate a scan of the the package the class with annotation is defined. therefore, if all components are in sub packages, no need to define component scan explicitly
what does @Component signify?
notify spring to manage the bean
what does @autowire signify?
notify spring should find the matching bean and wire the dependency in
what is the difference between @controller, @component, @repository and @service annotations in spring ?
@component: generic component
@repository: encapsulating storage, retrieval, and search behvaiour typically from a relational database. spring will automatically add exception translation for JDBC exceptions into spring exception
@service : business service facade
@controller: controller in MVC pattern
specific annotations signify the component is for specific layer and allow for AOP process on specific layer only
what is the default scope of a bean?
what are the other scopes available?
singleton - one instance per spring context
prototype - new bean whenever requested
request - one bean per HTTP request, web-aware spring applicationContext
session - one bean per HTTP session. web-aware spring ApplicationContext
by default singleton type
are spring beans thread safe?
not thread safe by default as singleton by default. one bean for multiple threads execution. to be thread safe, need ot use other scope types of beans to have a new bean per thread
how is spring’s singleton bean different from gang of four singleton pattern?
gang of four defines singleton as having one and only one instance per ClassLoader. however, spring singleton is defined as one instance of bean definition per container. so if multiple spring ApplicationContext exist, then more than one singleton can exist
what are the different types of dependecy injections?
what is setter injection?
what is constructor injection?
two ways to inject setter vs constructor
setter: @autowired on top of setter method in parent component. when setter method is not defined, @autowired on top of a property directly
constructor: @autowired on constructor method
how do you choose between setter and constructor injections ?
two types of dependecy: optional and mandatory
spring recommends constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null
when use constructor, if too many dependecies, it is obvious in the contructor method. highlight refatorying is required as bean is doing too many jobs
setter injection will mutate object one property at one time. if dependecy is null, setter still allow it to happen as optional dependecy
therefore, use constructor injection for mandatory dependecy and setter for optional
what are the different options available to create applicationContext for spring?
what is the difference between XML and java configurations for spring?
how do you choose between xml and java configurations for spring ?
with use of annotations, the things that are specified in a applicationContext are at bare minimum.
there is little to choose between these as long as the configuration is at a bare minimum
with spring boot, slowly moving to using java configuration as less configuration need to be done compare to loading configuration from xml
how does spring do autowiring?
what are the different kinds of matching used by spring for autowiring ?
by type - class or interface. if dependecies is interface, search for implementation
by name - multiple implementations for an interface, depends on the bean name used in caller e.g. @Autowired serviceInterface serviceImplementationMethodClassName
constructor - similar to by type
how do you debug problems with spring bean definition ?
NoUNiqueBeanDefinitionException: more than one matching components to implement interface and name used in caller is not helping to determine which one
NoSuchBeanDefinitionException : not annotated with @component properly or component scan is not proper
what is @Primary?
when multiple beans found matching, primay one is returned by default
what is @Qualifier
e.g. @Autowired @Qualifier(“qualifier name”) on calling side, on component also add @Qualifier(“qualifier name”)
what is CDI contexts and dependecy injection?
does spring support CDI?
JAVA EE dependency injection standard JSR-330
API tries to standardize dependency injection
spring supports most annotations in the standard
- @inject = @autowired
- @named = @component @ qualifier
- @Singleton defined a scope of Singleton
would you recommend to use CDI or spring annotations ?
CDI is a standard. spring has more complementing features usually compare to the standard
what are the major features in different versions of spring?
what are the new features in spring framewor 4.0?
what are the new features in spring framework 5.0 ?
spirng 2.5 made annotation-driven configuration possible
spring 3.0 made great use of java 5 improvements in language
spring 4.0 first version to fully support java 8 features
min version of java to use spring 4 is java se 6
introduced @RestController annotation. useful for restful services
spring 4.1 supports JCache JSR-107 annotations
spring 5.0: functional web framework, suuport for jigsaw (java modularity to reduce memory cost java), support for reactive programming(building applications around events), support for kotlin(reduce lines of code)
spring @controller vs @restcontroller
@restcontroller is a specialized version of @controller introduced in spring 4.0. it indicates a controller in a RESTful web service
@restcontroller = @controller + @responsebody. therefore, no need to add @responsebody annotation for every handler method
@controller is introduced in spring 2.5
what are the important spring modules?
modules for different tier / layer in web application architecture and also cross-cutting concerns
1. data access / integration: for data layer in web application. jdbc, orm, oxm, JMS(talk to other service over message queues), Transactions
2. web: web socket, servlet, web, portlet
3. core container:beans, core, context, SpEl (spring expression language to support bean definition)
4. test
5. cross-cutting: AOP(aspect oriented programming), Aspects, instrumentation, messaging
all modules share the same version as spring framework e.g. spring 4.0, all modules have 4.0 as release version
what are the spring projects ?
spring boot :quick build application
spring cloud: build cloud native application
spring data: consistent data access to veriaty of databases e.g. nosql
spring batch: batch applications
spring security: secutiry
spring HATEOAS: HATEOAS return data and related links for resources
what is the simplest way of ensuring that we are using single version of all spring related dependecies?
use BOM bill of material. all spring modules will use the same version
<artifactId>spring-framework-bom</artifactId>
<version>5.0.0.RELEASE</version>
what are some of the design patterns used in spring framework?
front controller - dispather servlet
prototype - beans
dependency injection
factory pattern - bean factory & applicationContext
template method - abstract method, jdbc template. provide a basic template wrapper. allow coder to override the common abstract methods
what are some of the important spring annotations?
@component, @service, @repository, @controller @autowired @primary @qualifier @configuration
what do you think about spring framework? why is spring popular?
can you give a big picture of the spring framework?
architecture - flexible & no restrictions. good support for many technologoes e.g. aspectJ, jsp,
design - loosely coupled
code - easy unit testing
features - dependency injection, IOC container, autowiring component scan
spring modules - useful
spring projects - increase usability and easy to work
What is dependency
injection
Dependency Injection is a technique of creating software in which objects do not create their
dependencies on itself, instead objects declare dependencies that they need and it is external
object job or framework job to provide concrete dependencies to objects.
Types of Dependency Injection:
Constructor injection
Setter injection
Interface injection
Advantages of using dependency injection is:
Increases code reusability
Increases code readability
Increases code maintainability
Increases code testability
Reduces coupling
Increases cohesion
What is a pattern?
A Software Design Pattern is a reusable solution to often, commonly occurring problem in
software design. It is a high level description on how to solve the problem, that can be used in
many different situations. Design patterns often represent best practices that developers can use
to solve common problems.
Some examples of commonly used design patterns from GoF Design Patterns:
Factory Method
Builder
Template Method
Strategy
Observer
Visitor
Facade
Composite
Dependency Injection is a pattern that solves problem of flexible dependencies creation.
What is an antipattern?
Anti-pattern is ineffective and counter-productive solution to often occurring problem.
Examples of Anti-patterns in Object Oriented Programming:
God Object (object doing too much responsibilities. hard to change and test)
Sequential coupling (methods must be called in particular sequence, otherwise will have exceptions)
Circular dependency
Constant interface (constants in interface that can be exposed to API)
What is an interface and what are the
advantages of making use of them in Java?
OOP Definition – An interface is a description of actions that object can do, it is a way to
enforce actions on object that implements the interface
Java Definition – An interface is a reference type, which contains collections of abstract
method. Class that implements the interface, must implement all methods from this
interface, or it needs to declare methods as abstract if object does not know how to
implement specified method. Java Interface may contain also:
Constants
Default Methods (Java 8)
Static methods
Nested types
Advantages of using interfaces in Java:
Allows decoupling between contract and its implementation
Allows declaring contract between callee and caller
Increases interchangeability
Increases testability
Advantages of using interfaces in Spring:
Allows for use of JDK Dynamic Proxy
Allows implementation hiding (implementation classes for the same interface can be declared as package access only. spring will expose the interface to caller class and inject respective implementation class)
Allows to easily switch beans (allow changing implementation class of the same interface without changing the caller class implementation details)
What is meant by “applicationcontext?
Application Context is a central part of Spring application. It holds bean definitions and contains
registry of application components. It allows you to retrieve assembled and configured beans.
Application Context:
Initiates Beans
Configures Beans
Assemblies Beans (resolve properties and inject dependencies)
Manages Beans Lifecycle
Is a Bean Factory
Is a Resource Loader
Has ability to push events to registered even listeners
Exposes Environment which allows to resolve properties
Common Application Context types:
AnnotationConfigApplicationContext (mostly used)
AnnotationConfigWebApplicationContext (same as 1st but for web app)
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
XmlWebApplicationContext
What is the concept of a “container”?
Container is an execution environment which provides additional technical services for
your code to use. Usually containers use IoC technique, that allows you to focus on
creating business aspect of the code, while technical aspects like communication details
(HTTP, REST, SOAP) are provided by execution environment.
Spring provides a container for beans. It manages lifecycle of the beans and also provides
additional services through usage of Application Context.
Spring Container Lifecycle:
- Application is started.
- Spring container is created.
- Containers reads configuration.
- Beans definitions are created from configuration.
- BeanFactoryPostProcessors are processing bean definitions.
- Instances of Spring Beans are created.
- Spring Beans are configured and assembled – resolve property values and inject
dependencies. - BeanPostProcessors are called.
- Application Runs.
- Application gets shutdown.
- Spring Context is closed.
- Destruction callbacks are invoked.
- How are you going to create a new
instance of an ApplicationContext?
Non-Web Applications:
AnnotationConfigApplicationContext
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
Web Applications:
Servlet 2 – web.xml, ContextLoaderListener, DispatcherServlet
Servlet 3 – XmlWebApplicationContext
Servlet 3 - AnnotationConfigWebApplicationContext
Spring Boot: (create application context automatically. no manual configuration required)
SpringBootConsoleApplication – CommandLineRunner
SpringBootWebApplication – Embedded Tomcat
Can you describe the lifecycle of a
Spring Bean in an ApplicationContext?
Context is Created:
1. Beans Definitions are created based on Spring Bean Configuration.
2. BeanFactoryPostProcessors are invoked.
Bean is Created:
1. Instance of Bean is Created.
2. Properties and Dependencies are set.
3. BeanPostProcessor::postProcessBeforeInitialization gets called.
4. @PostConstruct method gets called.
5. InitializingBean::afterPropertiesSet method gets called.
6. @Bean(initMethod) method gets called
7. BeanPostProcessor::postProcessAfterInitialization gets called.
Bean is Ready to use.
Bean is Destroyed:
1. @PreDestroy method gets called.
2. DisposableBean::destroy method gets called.
3. @Bean(destroyMethod) method gets called.
How are you going to create an
ApplicationContext in an integration test?
- Make sure that you have spring-test dependency added:
- Add Spring Runner to your test (@RunWith(SpringRunner.class))
- Add Context Configuration to your test @ContextConfiguration(classes= ApplicationConfiguration.class)
What is the preferred way to close an application context? Does Spring Boot do this for you?
Standalone Non-Web Applications
Register Shutdown hook by calling ConfigurableApplicationContext#registerShutdownHook –
Recommended way
Call ConfigurableApplicationContext#close
Web Application
ContextLoaderListener will automatically close context when web container will stop web application
Spring Boot
Application Context will be automatically closed
Shutdown hook will be automatically registered
ContextLoaderListener applies to Spring Boot Web Applications as well
Dependency Injection using Java Configuration (i.e. use @Configuration to register beans )
When using Dependency Injection using Java Configuration you need to explicitly define all your beans
and you need to use @Autowire on @Bean method level to inject dependencies.
what is Dependency Injection process using Spring Annotations (i.e. @Component, @Controller etc)?
- Create classes annotated with @Component annotations or other stereotypes
- Define dependencies when required in each caller bean
- Create Configuration with Component Scanning Enabled
what is Component Scanning?
Process in which Spring is scanning Classpath in search for classes annotated with stereotypes annotations (@Component, @Repository, @Service, @Controller, …) and based on those creates beans
definitions
Simple component scanning within Configuration package and all subpackages
Advanced Component Scanning Rules
- define base class or package to scan
- include or exclude filters etc
what are Stereotypes?
Stereotypes are annotations applied to classes to describe role which will be performed by this class.
Spring discovered classes annotated by stereotypes and creates bean definitions based on those types.
Types of stereotypes
Component – generic component in the system, root stereotype, candidate for autoscanning
Service – class will contain business logic
Repository – class is a data repository (used for data access objects, persistence)
Controller – class is a controller, usually a web controller (used with @RequestMapping)
stereotypes can be used interchangeably as the description is more for human interpretation. functionally still the same. e.g. change @Service to @Component. howver, if advanced usage like AOP is applied to certain types of stereotypes, then not cannot be changed
what are Meta-Annotations?
Meta-annotations are annotations that can be used to create new annotations.
e.g. @RestController annotation is using @Controller and @ResponseBody to define its behavior
Scopes of Spring Beans
Singleton: Single Bean per Spring Container - Default
Prototype: New Instance each time Bean is Requested
Request: New Instance per each HTTP Request
Session: New Instance per each HTTP Session
Application: One Instance per each ServletContext
Websocket: One Instance per each WebSocket
Are beans lazily or eagerly instantiated by default?
Lazy and Eager Instance Creation vs Scope Type:
Singleton Beans are eagerly instantiated by default
Prototype Beans are lazily instantiated by default (instance is created when bean is requested)
however, if Singleton Bean has dependency on Prototype Bean, then Prototype Bean Instance will be created eagerly to
satisfy dependencies for Singleton Bean
How do you alter bean initialization lazy or eager behavior?
- You can change default behavior for all beans by @ComponentScan annotation (@ComponentScan(lazyInit=true))
Setting lazyInit to true, will make all beans lazy, even Singleton Beans
Setting lazyInit to false (default), will create Singleton Beans Eagerly and Prototype Beans Lazily - You can also change default behavior by using @Lazy annotation:
@Lazy annotation takes one parameter - Whether lazy initialization should occur
By default @Lazy is used to mark bean as lazily instantiated
You can use @Lazy(false) to force Eager Instantiation – use case for @ComponentScan(lazyInit = true) when some beans
always needs to be instantiated eagerly - @Lazy can be applied to:
Classed annotated with @Component – makes bean Lazy or as specified by @Lazy parameter
Classes annotated with @Configuration annotation – make all beans provided by configuration lazy or as specified by @Lazy parameter e.g. @Configuration @Lazy for java configuration bean class
Method annotated with @Bean annotation – makes bean created by method Lazy or as specified by @Lazy parameter. configuration class individual bean level
What is a property source? How would you use
@PropertySource?
PropertySource is Spring Abstraction on Environment Key-Value pairs, which can come from:
JVM Properties
System Environmental Variables
JNDI Properties
Servlet Parameters
Properties File Located on Filesystem
Properties File Located on Classpath
You read properties with usage of @PropertySource or @PropertySources annotation:
e.g. @PropertySources({@PropertySource(..path),@PropertySource(…path)})
You access properties with usage of @Value annotation:
@Value(“${key-name}”)
private String name
What is a BeanFactoryPostProcessor and what is it used for?
When is it invoked? Why would you define a static @Bean method for BeanFactoryPostProcessor?
BeanFactoryPostProcessor is an interface that contains single method postProcessBeanFactory, implementing it allows you to create logic that will modify Spring Bean Metadata before any Bean is
created. BeanFactoryPostProcessor does not create any beans, however it can access and alter Metadata that is used later to create Beans.
BeanFactoryPostProcessor is invoked after Spring will read or discover Bean Definitions, but before any Spring Bean is created.
Because BeanFactoryPostProcessor is also a Spring Bean, but a special kind of Bean that should be invoked before other types of beans get created, Spring needs to have ability to create it before any
other beans. This is why BeanFactoryPostProcessors needs to be registered from static method level.
@Bean
public staticcustomBeanFactoryPostProcessor customBeanFactoryPostProcessor() {
return new customBeanFactoryPostProcessor();
}
What is a ProperySourcesPlaceholderConfigurer used for?
PropertySourcesPlaceholderConfigurer is a BeanFactoryPostProcessor that is used to resolve properties placeholder in Spring Beans on fields annotated with @Value(“${property_name}”).
What is a BeanPostProcessor and how is it different to a
BeanFactoryPostProcessor? What do they do?
When are they called?
BeanPostProcessor is an interface that allows you to create extensions to Spring Framework that will modify
Spring Beans objects during initialization. This interface contains two methods:
postProcessBeforeInitialization
postProcessAfterInitialization
Implementing those methods allows you to modify created and assembled bean objects or even switch object
that will represent the bean.
Main difference compared to BeanFactoryPostProcessor is that BeanFactoryPostProcessor works with Bean Definitions while BeanPostProcessor works with Bean Objects.
BeanFactoryPostProcessor and BeanPostProcessor in Spring Container Lifecycle
1. Beans Definitions are created based on Spring Bean Configuration.
2. BeanFactoryPostProcessors are invoked.
3. Instance of Bean is Created.
4. Properties and Dependencies are set.
5. BeanPostProcessor::postProcessBeforeInitialization gets called.
6. @PostConstruct method gets called.
7. InitializingBean::afterPropertiesSet method gets called.
8. @Bean(initMethod) method gets called
9. BeanPostProcessor::postProcessAfterInitialization gets called.
Recommended way to define BeanPostProcessor is through static @Bean method in Application Configuration. This is because BeanPostProcessor should be created early, before other Beans Objects are ready.
What is an initialization method and how is it declared on a Spring bean?
Initialization method is a method that you can write for Spring Bean if you need to perform some initialization code that depends on properties and/or dependencies injected into Spring Bean.
it is not recommended to initialize in constructor as properties or dependencies may not be ready at construction
You can declare Initialization method in three ways:
Create method in Spring Bean annotated with @PostConstruct
Implement InitializingBean::afterPropertiesSet
Create Bean in Configuration class with @Bean method and use
@Bean(initMethod)
What is a destroy method, how is it declared on a Spring bean?
Destroy method is a method in Spring Bean that you can use to implement any cleanup logic for resources used by the Bean. Method will be called when Spring Bean will be taken out of use, this is usually happening when Spring Context is closed. e.g. DB connection bean should destroy to close connections
You can declare destroy method in following ways:
Create method annotated with @PreDestroy annotation
Implement DisposableBean::destroy
Create Bean in Configuration class with @Bean method and use
@Bean(destroyMethod)
Consider how you enable JSR-250 annotations like @PostConstruct and @PreDestroy in Spring?
When using AnnotationConfigApplicationContext support for @PostConstruct and @PreDestroy is added automatically.
Those annotations are handled by CommonAnnotationBeanPostProcessor with is automatically registered by AnnotationConfigApplicationContext.
When/how will they (initialization, destroy methods) get called?
Context is Created:
1. Beans Definitions are created based on Spring Bean Configuration.
2. BeanFactoryPostProcessors are invoked.
Bean is Created:
1. Instance of Bean is Created.
2. Properties and Dependencies are set.
3. BeanPostProcessor::postProcessBeforeInitialization gets called.
4. @PostConstruct method gets called.
5. InitializingBean::afterPropertiesSet method gets called.
6. @Bean(initMethod) method gets called
7. BeanPostProcessor::postProcessAfterInitialization gets called. Bean is Ready to use.
Bean is Destroyed (usually when context is closed):
1. @PreDestroy method gets called.
2. DisposableBean::destroy method gets called.
3. @Bean(destroyMethod) method gets called.
What does component-scanning do?
Process in which Spring is scanning Classpath in search for classes annotated with stereotypes annotations (@Component, @Repository, @Service, @Controller, …) and based on those creates beans definitions.
Simple component scanning within Configuration package and all subpackages
Advanced Component Scanning Rules e.g. base package, include, exclude patterns
What is the behavior of the annotation @Autowired?
@Autowired is an annotation that is processed by AutowiredAnnotationBeanPostProcessor, which can be put onto class constructor, field, setter method or config method. Using this annotation enables automatic Spring Dependency Resolution that is primary based on types.
@Autowired has a property required which can be used to tell Spring if dependency is required or optional. By default dependency is required. If @Autowired with required dependency is used on top
of constructor or method that contains multiple arguments, then all arguments are considered required dependency unless argument is of type Optional, is marked as @Nullable, or is marked as @Autowired(required = false).
If @Autowired is used on top of Collection or Map then Spring will inject all beans matching the type into Collection and key-value pairs as BeanName-Bean into Map. Order of elements depends on usage of @Order, @Priority annotations and implementation of Ordered interface.
e.g. List<InterfaceClassName> means get all implementation classes for the same interface injected</InterfaceClassName>
Bean Resolution Logic
@Autowired uses following steps when resolving dependency:
1. Match exactly by type, if only one found, finish.
2. If multiple beans of same type found, check if any contains @Primary annotation, if yes, inject @Primary bean and finish.
3. If no exactly one match exists, check if @Qualifier exists for field, if yes use @Qualifier to find matching bean.
4. If still no exactly one bean found, narrow the search by using bean name.
5. If still no exactly one bean found, throw exception (NoSuchBeanDefinitionException, NoUniqueBeanDefinitionException, …).
What is the behavior of the annotation @Autowired with regards to field injection?
@Autowired
public DbRecordsReader recordsReader;
@Autowired
protected DbRecordsBackup recordsBackup;
@Autowired
private DbRecordsProcessor recordsProcessor;
@Autowired
DbRecordsWriter recordsWriter;
Autowired fields can have any visibility level
Injection is happening after Bean is created but before any init method (@PostConstruct,
InitializingBean, @Bean(initMethod)) is called
By default field is required, however you can use Optional, @Nullable or
@Autowired(required = false) to indicate that field is not required.
What is the behavior of the annotation @Autowired with
regards to constructor injection?
@Autowired
public RecordsService(DbRecordsReader recordsReader, DbRecordsProcessor recordsProcessor) {
this.recordsReader = recordsReader;
this.recordsProcessor = recordsProcessor;
}
Constructor can have any access modifier (public, protected, private, package-private).
If there is only one constructor in class, there is no need to use @Autowired on top of it, Spring will use this default constructor anyway and will inject dependencies into it.
If class defines multiple constructor, then you are obligated to use @Autowired to tell Spring which constructor should be used to create Spring Bean. If you will have a class with multiple constructor without any of constructor marked as @Autowired then Spring will throw NoSuchMethodException.
By default all arguments in constructor are required, however you can use Optional, @Nullable or @Autowired(required = false) to indicate that parameter is not required.
What is the behavior of the annotation @Autowired with
regards to method injection?
@Autowired
public void setRecordsReader(DbRecordsReader recordsReader) {
this.recordsReader = recordsReader;
}
@Autowired method can have any visibility level and also can contain multiple parameters. If method contains multiple parameters, then by default it is assumed that in @Autowired method all parameters
are required. If Spring will be unable to resolve all dependencies for this method, NoSuchBeanDefinitionException or NoUniqueBeanDefinitionException will be thrown.
When using @Autowired(required = false) with method, it will be invoked only if Spring can resolve all parameters.
If you want Spring to invoke method only with arguments partially resolved, you need to use @Autowired method with parameter marked as Optional, @Nullable or @Autowired(required= false) to indicate that this parameter is not required.
What do you have to do, if you would like to inject something into a private field? How does this impact testing?
Injection of dependency into private field can be done with @Autowired annotation:
Injection of property into private field can be done with @Value annotation:
Private Field cannot be accessed from outside of the class, to resolve this when writing Unit Test you can
use following solutions:
Use SpringRunner with ContextConfiguration and @MockBean
Use ReflectionTestUtils to modify private fields
Use MockitoJUnitRunner to inject mocks
Use @TestPropertySource to inject test properties into private fields
How does the @Qualifier annotation complement the use of @Autowired?
@Qualifier annotation gives you additional control on which bean will be injected, when multiple beans of the same type are found. By adding additional information on which bean you want to inject, @Qualifier resolves issues with NoUniqueBeanDefinitionException.
You can use @Qualifier in three ways:
At injection point with bean name as value (spring will resolve qualifier name to bean class name and find if matching)
At injection and bean definition point (can name in any format)
Custom Qualifier Annotation Definition
What is a proxy object?
Proxy Object is an object that adds additional logic on top of object that is being proxied without having to modify code of proxied object. Proxy object has the same public methods as object that is being proxied and it should be as much as possible indistinguishable from proxied object. When method is invoked on Proxy Object, additional code, usually before and after sections are invoked, also code from proxied object is invoked by Proxy Object.
methods(args) =» proxy object =» methods(args) =» proxied object
what are the two different types of proxies Spring can create? What are the limitations of these proxies (per type)?
Spring Framework supports two kind of proxies:
JDK Dynamic Proxy – used by default if target object implements interface
CGLIB Proxy – use when target does not implement any interface
Limitations of JDK Dynamic Proxy:
Requires proxy object to implement the interface
Only interface methods will be proxied
No support for self-invocation (calling own method from another own method)
Limitations of CGLIB Proxy:
Does not work for final classes
Does not work for final methods
No support for self-invocation
What is the power of a proxy object and where are the disadvantages?
Proxy Advantages:
Ability to change behavior of existing beans without changing original code
Separation of concerns (logging, transactions, security, …)
Proxy Disadvantages:
May create code hard to debug
Needs to use unchecked exception for exceptions not declared in original method
May cause performance issues if before/after section in proxy code is using IO (Network, Disk)
May cause unexpected equals operator (==) results since Proxy Object and Proxied Object are two different objects
What are the advantages of Java Config? What are the limitations?
Advantages of Java Config over XML Config:
Compile-Time Feedback due to Type-checking (XML will always compile success and throw error during runtime)
Refactoring Tools for Java without special support/plugins work out of the box with Java Config (special support needed for XML Config)
Advantages of Java Config over Annotation Based Config:
Separation of concerns – beans configuration is separated from beans implementation
Technology agnostic – beans may not depend on concrete IoC/DI implementation – makes it easier to switch technology
Ability to integrate Spring with external libraries (external classes cannot be annotated as beans directly)
More centralized location of bean list
Limitations of Java Config:
Configuration class cannot be final (Spring creates CGLIB proxy to access ApplicationConfig class and methods to ensure beans are singleton and only created once by default)
Configuration class methods cannot be final
All Beans have to be listed, for big applications, it might be a challenge compared to Component Scanning
What does the @Bean annotation do?
@Bean annotation is used in @Configuration class to inform Spring that instance of class returned by method annotated with @Bean will return bean that will be managed by Spring.
@Bean also allows you to:
Specify init method – will be called after instance is created and assembled (dependencies injected)
Specify destroy method – will be called when bean is discarded (usually when context is getting closed)
Specify name for the bean – by default bean has name autogenerated based on method name, however this can be overridden
Specify alias/aliases for the bean
Specify if Bean should be used as candidate for injection into other beans – default true
Configure Autowiring mode – by name or type (Deprecated since Spring 5.1)
What is the default bean id if you only use @Bean? How can you override this?
When using @Bean without specifying name or alias, default bean id will be created based on name of the method which was annotated with @Bean annotation.
@Bean
public SpringBean1 springBean1() {
return new SpringBean1();
}
bean id = springBean1
You can override this behavior by specifying name or aliases for the bean.
@Bean(name = “2ndSpringBean”)
public SpringBean2 springBean2() {
return new SpringBean2();
}
bean id = 2ndSpringBean
@Bean(name = {“3rdSpringBean”, “thirdSpringBean”})
public SpringBean3 springBean3() {
return new SpringBean3();
}
bean id = 3rdSpringBean, alias=thirdSpringBean
Why are you not allowed to annotate a final class with @Configuration? Why can’t @Bean methods be final either?
Class annotated with @Configuration cannot be final because Spring will use CGLIB to create a proxy for @Configuration class. CGLIB creates subclass for each class that is supposed to be proxied,
however since final class cannot have subclass CGLIB will fail. This is also a reason why methods cannot be final, Spring needs to override methods from parent class for proxy to work correctly, however final
method cannot be overridden, having such a method will make CGLIB fail.
If @Configuration class will be final or will have final method, Spring will throw BeanDefinitionParsingException.
How do @Configuration annotated classes support
singleton beans?
Spring supports Singleton beans in @Configuration class by creating CGLIB proxy that intercepts calls to the method. Before method is executed from the proxied class, proxy intercept a call and checks if instance of the bean already exists, if instance of the bean exists, then call to method is not allowed and already existing instance is returned, if instance does not exists, then call is allowed, bean
is created and instance is returned and saved for future reuse. To make method call interception CGLIB proxy needs to create subclass and also needs to override methods.
Easiest way to observe that calls to original @Configuration class are proxied is with usage of debugger or by printing stacktrace. When looking at stacktrace you will notice that class which serves beans is not original class written by you but it is different class, which name contains $$EnhancerBySpringCGLIB.
How do you configure profiles?
Spring Profiles are configured by:
Specifying which beans are part of which profile
Specifying which profiles are active
You can specify beans being part of profile in following ways:
Use @Profile annotation at @Component class level – bean will be part of profile/profiles specified in annotation
Use @Profile annotation at @Configuration class level – all beans from this configuration will be part of profile/profiles specified in annotation
Use @Profile annotation at @Bean method of @Configuration class – instance of bean returned by this method will be part of profile/profiles specified in annotation
Use @Profile annotation to define custom annotation -@Component / @Configuration / @Bean method annotated with custom annotation will be part of profile/profiles specified in annotation
If Bean does not have profile specified in any way, it will be created in every profile.
You can use ‘!’ to specify in which profile bean should not be created.
You can activate profiles in following way:
Programmatically with usage of ConfigurableEnvironment
By using spring.profiles.active property
On JUnit Test level by using @ActiveProfiles annotation
In Spring Boot Programmatically by usage of SpringApplicationBuilder
In Spring Boot by application.properties or on yml level
What are possible use cases where spring profiles might be useful?
Spring Profiles are useful in following cases:
Changing Behavior of the system in Different Environments by changing set of Beans that are
part of specific environments, for example prod, cert, dev
Changing Behavior of the system for different customers
Changing set of Beans used in Development Environment and also during Testing Execution
Changing set of Beans in the system when monitoring or additional debugging capabilities should be turned on
Can you use @Bean together with @Profile?
Yes, @Bean annotation can be used together with @Profile inside class annotated with @Configuration annotation on top of method that returns instance of the bean.
If, method annotated with @Bean does not have @Profile, that beans that this bean will exists in all profiles.
You can specify one, multiple profiles, or profile in which bean should not exists:
@Profile(“database”)
@Profile(“!prod”)
@Profile({“database”, “file”})
Can you use @Component together with @Profile?
Yes, @Profile annotation can be used together with @Component on top of class representing spring bean.
If, class annotated with @Component does not have @Profile, that beans that this bean will exists in all profiles.
You can specify one, multiple profiles, or profile in which bean should not exists:
@Profile(“database”)
@Profile(“!prod”)
@Profile({“database”, “file”})
How many profiles can you have?
Spring Framework does not specify any explicit limit on number of profiles, however since some of the classes in Framework, like ActiveProfilesUtils used by default implementation of ActiveProfilesResolver are using array to iterate over profiles, this enforces inexplicit limit that is equal to maximum number of elements in array that you can have in Java, which is Integer.MAX_VALUE - 2,147,483,647 (2^31 − 1).
How do you inject scalar/literal values into Spring beans?
To inject scalar/literal values into Spring Beans, you need to use @Value annotation.
@Value annotation has one field value that accepts:
Simple value
Property reference
SpEL String
@Value annotation can be used on top of:
Field
Constructor Parameter
Method – all fields will have injected the same value
Method parameter – Injection will not be performed automatically if @Value is not present on method level or if @Autowired is not present at method level
Annotation type
Inside @Value you can specify:
Simple value - @Value(“John”), @Value(“true”)
Reference a property - @Value(“${app.department.id}”)
Perform SpEL inline computation - @Value(“#{‘Wall Street’.toUpperCase()}”),
@Value(“#{5000 * 0.9}”),
@Value(“#{‘${app.department.id}’.toUpperCase()}”)
Inject values into array, list, set, map
What is @Value used for?
@Value is used for:
Setting simple values of Spring Bean Fields, Method Parameters, Constructor Parameters
Injecting property/environment values into Spring Bean Fields, Method Parameters, Constructor Parameters
Injecting results of SpEL expressions into Spring Bean Fields, Method Parameters, Constructor Parameters
Injecting values from other Spring Beans into Spring Bean Fields, Method Parameters, Constructor Parameters
Injecting values into collections (arrays, lists, sets, maps) from literals, property/environment values, other Spring Beans
Setting default values of Spring Bean Fields, Method Parameters, Constructor Parameters when referenced value is missing
What is Spring Expression Language (SpEL for short)?
Spring Expression Language (SpEL) is an expression language that allows you to query and manipulate objects graphs during the runtime. SpEL is used in different products across Spring portfolio.
SpEL can be used independently with usage of ExpressionParser and EvaluationContext or can be used on top of fields, method parameters, constructor arguments via @Value annotation @Value(“#{ … }”).
What is the Environment abstraction in Spring?
Environment Abstraction is part of Spring Container that models two key aspect of application environment:
Profiles
Properties
Environment Abstraction is represent on code level by classes that implements Environment interface. This interface allows you to resolve properties and also to list profiles. You can receive reference to class that implements Environment by calling EnvironmentCapable class, implemented by ApplicationContext.
Properties can also be retrieved by using @Value(“${…}”) annotation.
Environment Abstraction role in context of profiles is to determine which profiles are currently active, and which are activated by default.
Environment Abstraction role in context of properties is to provide convenient, standarized and generic service that allows to resolve properties and also to configure property sources.
Properties may come from following
sources:
Properties Files
JVM system properties
System Environment Variables
JNDI
Servlet Config
Servlet Context Parameters
Default property sources for standalone applications are configured in StandardEnvironment, which includes JVM system properties and System Environment Variables. When running Spring Application in Servlet Environment, property sources will be configured based on StandardServletEnvironment, which additionally includes Servlet Config and Servlet Context Parameters, optionally it might include
JndiPropertySource.
To add additional properties files as property sources you can use @PropertySource annotation.
Where can properties in the environment come from?
Property Sources in Spring Application vary based on type of applications that is being executed:
Standalone Application
Servlet Container Application
Spring Boot Application
Property Sources for Standalone Spring Framework Application:
Properties Files
JVM system properties
System Environment Variables
Property Sources for Servlet Container Spring Framework Application:
Properties Files
JVM system properties
System Environment Variables
JNDI
ServletConfig init parameters
ServletContext init parameters
Property Sources for Spring Boot Application:
Devtools properties from ~/.spring-boot-devtools.properties (when devtools is active)
@TestPropertySource annotations on tests
Properties attribute in @SpringBootTest tests
Command line arguments
Properties from SPRING_APPLICATION_JSON property
ServletConfig init parameters
ServletContext init parameters
JNDI attributes from java:comp/env
JVM system properties
System Environment Variables
RandomValuePropertySource - ${random.*}
application-{profile}.properties and YAML variants - outside of jar
application-{profile}.properties and YAML variants – inside jar
application.properties and YAML variants - outside of jar
application.properties and YAML variants - inside jar
@PropertySource annotations on @Configuration classes
Default properties - SpringApplication.setDefaultProperties
What can you reference using SpEL?
You can reference following using SpEL:
Static Fields from class - T(com.example.Person).DEFAULT_NAME
Static Methods from class - T(com.example.Person).getDefaultName()
Spring Bean Property - @person.name
Spring Bean Method - @person.getName()
SpEL Variables - #personName
Object property on reference assigned to SpEL variables - #person.name
Object method on reference assigned to SpEL variables - #person.getName()
Spring Application Environment Properties - environment[‘app.file.property’]
System Properties - systemProperties[‘app.vm.property’]
System Environment Properties - systemEnvironment[‘JAVA_HOME’]
What is the difference between $ and # in @Value
expressions?
@Value annotation supports two types of expressions:
Expressions starting with $ - used to reference a property in Spring Environment Abstraction
Expressions starting with # - SpEL expressions parsed and evaluated by SpEL