Any RuntimeException (unchecked exception) or Error will cause by default a rollback. Checked exceptions don’t cause a rollback
1. MVC is an abbreviation for a design pattern. What does it stand for and what is the idea behind it?
Model–View–Controller software architectural pattern is designed to decouple three components, each of them can be easily swapped with a different implementation, and together they provide a fully functional user interface.
Advantages:
Spring MVC Request Life Cycle
@RequestMappin
g annotation at the type or method level within controller classes.2. Do you need spring-mvc.jar in your classpath or is it part of spring-core?
3. What is the DispatcherServlet and what is it used for?
DispatcherServlet is a front controller that receives all requests and delegates them to all the required controllers. But it is involved in more steps than just the first one. Among these are:
This servlet initializes a WebApplicationContext that is a child of root ApplicationContext.
Front controller pattern stands for a single servlet delegates responsibility for a request to other components of an application, to perform actual processing.
Following front controller pattern, Spring MVC provides DispatcherServlet
receiving all the requests and delegates the processing to request handlers (controllers). Once the processing is done, ViewResolver will render a view based on the view name.
A Spring web application may define multiple dispatcher servlets, each of which has its own namespace, its own Spring application context and its own set of mappings and handlers.
Used for
To enable Spring MVC within a web application
WebApplicationContext
Use Java to configure DispatcherServlet in the servlet container
public class DemoWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected String[] getServletMappings() { return new String[] { "/" }; // Map DispatcherServlet to / } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SecurityConfig.class, DataServiceConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { // Specify configuration class return new Class<?>[] { WebConfig.class }; } @Override protected Filter getServletFilters() { CharacterEncodingFilter cef = new CharacterEncodingFilter(); cef.setEncoding("UTF-8"); cef.setForceEncoding(true); return new Filter{ new HiddenHttpMethodFilter(), cef}; } }
To make things more practical, Spring class AbstractAnnotationConfigDispatcherServletInitializer
, an implementation of WebApplicationInitializer
, was extended because it contains concrete implementations of methods needed for the configuration of Spring web applications that use Java-based Spring configuration.
getRootConfigClasses()
: A root application context of type AnnotationConfigWebApplicationContext
will be created.getServletConfigClasses()
: A web application context of type AnnotationConfigWebApplicationContext will be createdgetServletMappings()
: The DispatcherServelt’s mappings (context) are specified by the array of strings returned by this method.getServletFilters()
: As the name of the methods says, this one will return an array of implementations of javax.servlet.Filter that will be applied to every requestBy providing an empty class that extends AbstractSecurityWebApplicationInitializer
, you are basically telling Spring that you want DelegatingFilterProxy
enabled, so springSecurityFilterChain
will be used before any other registered javax.servlet.Filter
.
AbstractAnnotationConfigDispatcherServletInitializer
will automatically be used to configure DispatcherServlet
and the Spring application context in the application’s servlet context.DispatcherServlet
and a ContextLoaderListener
.getServletMappings()
identifies one or more paths that DispatcherServlet will be mapped to. It will handle all requests coming into the application.getRootConfigClasses()
is called internally, and the configuration classes are used to create the root application context, which will become the parent ApplicationContext that contains bean definitions shared by all child (DispatcherServlet) contexts.In Spring Boot The spring-boot-starter-web starter by default configures DispatcherServlet to the URL pattern “/” and adds Tomcat as the embedded servlet container, which runs on port 8080. Spring Boot by default serves the static resources (HTML, CSS, JS, images, etc.) from the following CLASSPATH locations:
4. Is the DispatcherServlet instantiated via an application context?
DispatcherServlet can be instantiated in 2 different ways and in both it is initialized by the servlet container:
In short: the DispatcherServlet is not instantiated via an application context. It is instantiated before any application context is created. parent ApplicationContext is creted by ContextLoaderListener
, child ApplicationContext is created by Spring MVC DispatcherServlet
.
Spring MVC WebApplicationContext Hierarchy
Parent ApplicationContext
org.springframework.web.context.ContextLoaderListener
.Child ApplicationContext
DispatcherServlet
.We can have two DispatcherServlet instances in an application.
DispatcherServlet
can be instantiated in 2 different ways and in both it is initialized by the servlet container:
5. What is a web application context? What extra scopes does it offer?
WebApplicationContext is a Spring application context for web applications.
Comparing to ApplicationContext
WebApplicationContext
interface extends the ApplicationContext
interfaceIn addition to the standard Spring bean scopes singleton and prototype, there are three additional scopes available in a web application context:
ServletContext
The beans that are registered within the WebApplicationContext
can also access the Servlet Context by implementing the ServletContextAware
interface
public interface ServletContextAware extends Aware { void setServletContext(ServletContext servletContext); }
6. What is the @Controller annotation used for?
@Controller annotation is used to mark a class as a controller to be used by the DispatcherServlet to process requests. @Controller annotation is annotated by @Component so in case your DispatcherServlet creates a WebApplicationContext that is configured by component-scanning, that configuration will pick @Controller annotated classes automatically.
You can define controllers without component-scanning and in that case, you will have to implement the Controller interface and override handleRequest() method.
The core interface in Spring MVC is Controller. Spring simply requires that
The @EnableWebMvc
annotation enables the annotation support for Spring MVC, that is, the @Controller annotation.
The Dispatcher Servlet scans classes annotated with it to map the web requests to the methods annotated with @RequestMapping, which are mapped to a certain request URL
7. How is an incoming request mapped to a controller and mapped to a method?
When a request is issued to the application:
HandlerMapping
interface.8. What is the difference between @RequestMapping and @GetMapping?
@GetMapping
equals to ` @RequestMapping(method = RequestMethod.GET)`
9. What is @RequestParam used for?
The request parameter can be retrieved through a method argument annotated with @RequestParam
You can use the @RequestParam
annotation to bind Servlet request parameters.
By default, method parameters that use this annotation are required, but you can specify that a method parameter is optional by
@RequestParam
annotation’s required flag to false
orjava.util.Optional
wrapper.Type conversion is automatically applied if the target method parameter type is not String.
NB. use of @RequestParam
is optional. By default, any argument that is a simple value type (as determined by BeanUtils#isSimpleProperty) and is not resolved by any other argument resolver, is treated as if it were annotated with @RequestParam.
10. What are the differences between @RequestParam and @PathVariable?
@PathVariable
instructs Spring MVC to bind the path variable within the URL – for example, http:// localhost:8080/singer/1 into the id argument of the findSingerById() method. – Note that for the id argument, the type is Long, while Spring’s type conversion system will automatically handle the conversion from String to Long for us.
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public String show(@PathVariable("userId") Long id, Model model) {
// ...
}
Differences:
http://localhost:8080/greeting?firstName=dammy&lastName=good
http://localhost:8080/firstname/dammy/lastname/good
11. What are some of the parameter types for a controller method?
12. What other annotations might you use on a controller method parameter? (You can ignore
form-handling annotations for this exam)
13. What are some of the valid return types of a controller method?
14. What is a View and what’s the idea behind supporting different types of View?
View is responsible for presenting the data of the application to the user.
The user interacts with the view.
The core view resolver provided by Spring is the InternalResourceViewResolver
; it is the default view resolver.
Inside spring-webmvc.jar
there is a file called DispatcherServlet.properties
, and in it all default infrastructure beans are declared.
Spring MVC provides several view resolvers to support multiple view technologies, such as JSP, Velocity, FreeMarker, JSF, Tiles, Thymeleaf, and so on.
supporting different types of views:
15. How is the right View chosen when it comes to the rendering phase?
View Resolution Sequence
DispatcherServlet
ViewResolvers
are asked in sequence (based on their Order)16. What is the Model?
17. Why do you have access to the model in your View? Where does it come from?
18. What is the purpose of the session scope?
A session-scoped Spring bean exists for the lifetime of a HTTP session.
This enables creating, for instance, a session-scoped Spring bean that contains a shopping cart.
The bean instance will remain the same during all requests the user makes within one and the same HTTP session.
19. What is the default scope in the web context?
Singleton Scope is default scope.
20. Why are controllers testable artifacts?
The goal of Spring MVC Test is to provide an effective way to test controllers by performing requests and generating responses through the actual DispatcherServlet.
The Spring MVC Test Framework also provide full Spring MVC runtime behavior for tests without running in a servlet container.
@RunWith(SpringRunner.class) @WebMvcTest(HomeController.class) public class HomeControllerTest { @Autowired private MockMvc mockMvc;// Injects MockMvc @Test public void testHomePage() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("home")) .andExpect(content().string( containsString("Welcome to..."))); } }
21. What does a ViewResolver do?
ViewResolver
, that is a class implementing the ViewResolver interface, attempts to, given a view name and a locale, find a View.ViewResolver
attempts to map a view name to a View.InternalResourceViewResolver
; it is the default view resolver.@Configuration public class AppConfig { @Bean InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views"); resolver.setSuffix(".jspx" ); resolver.setRequestContextAttribute("requestContext"); return resolver; } }
1. What is Spring Boot?
Spring Boot is a preconfigured framework that works on top of the Spring Framework. It simplifies configuration for a Spring application by combining a group of common or related dependencies into single dependencies. Spring Boot is NOT a framework but rather, an easy way of creating stand-alone applications with little or no configurations.
Spring Boot Starters is one of the major key features or components of the Spring Boot Framework. The main responsibility of Spring Boot Starter is to combine a group of common or related dependencies into single dependencies. We need to define a lot of dependencies in our build files. It is a very tedious task for a Developer.
2. What are the advantages of using Spring Boot?
Spring Boot starters
These starters are pre-configured with the most commonly used library dependencies so you don’t have to search for the compatible library versions and configure them manually. E.g., the spring-boot-starter-data-jpa
starter module includes all the dependencies required to use Spring Data JPA, along with Hibernate library dependencies, as Hibernate is the most commonly used JPA implementation.
For example, if you have the spring-webmvc dependency in your classpath, Spring Boot assumes you are trying to build a SpringMVC-based web application and automatically tries to register DispatcherServlet if it is not already registered.
@PropertySource
configuration3. Why is it “opinionated”?
It makes assumptions and configures things for your application based on the dependencies in your classpath. By doing this, developers don’t have to waste time on configuration but instead, use their time on developing features.
Most of Spring application configuration is based on a common application.properties
or application.yml
file. If none is specified, it already has those property’s values as defaults.
4. What things affect what Spring Boot sets up?
Starters that are added to dependencies – only if @EnableAutoConfiguration or @SpringBoot application are used.
@ConditionalOnClass
, on the other hand @ConditionalOnMissingBean
@ConditionalOnBean
, @ConditionalOnMissingBean
How does it work? How does it know what to configure?
It scans dependencies in the classpath and then initializes “maybe” required beans. For example, if you have spring data on your classpath, then Spring Boot will create JPA repository bean.
Spring Boot provides many custom @Conditional
annotations to meet developers’ autoconfiguration needs based on various criteria, each of which can be used to control the creation of Spring beans.
@ConditionalOnClass
@ConditionalOnMissingClass
@ConditionalOnBean
@ConditionalOnMissingBean
@ConditionalOnProperty
@ConditionalOnResource
@ConditionalOnWebApplication
@ConditionalOnNotWebApplication
5. How are properties defined? Where is Spring Boot’s default property source?
Properties are usually defined in property files. Spring Boot default property source is application.properties or application.yml
6. Would you recognize common Spring Boot annotations and configuration properties if you saw them in the exam?
Spring Boot annotations include:
7. What is the difference between an embedded container and a WAR?
An embedded container is a server that comes with the resulting application whereas WAR is an archive that can be deployed on an external container.
A Standalone app uses your resources, web app executes on the server, rendering is done on your system.
An embedded container is packaged in the application JAR-file and will contain only one single application.
A WAR-file will need to be deployed to a web container, such as Tomcat, before it can be used. The web container to which the WAR-file is deployed may contain other applications.
Deployable WAR
packaging
type.
<packaging>war</packaging>
in Mavenapply plugin: 'war'
in Gradleyou need to add spring-boot-starter-tomcat
as the provided scope so that it won’t get packaged inside the WAR file.
SpringBootServletInitializer
sub-class and override its configure()
method. You can simply make your application’s entry point class extend SpringBootServletInitializer
.
@SpringBootApplication
public class SpringbootWebDemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringbootWebDemoApplication.class);
}
}
Now running the Maven/Gradle build tool will produce a WAR file that can be deployed on an external server.
8. What embedded containers does Spring Boot support?
Use Jettry rather than Tomcat
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> </dependencies>
9. What does @EnableAutoConfiguration do?
@EnableAutoConfiguration – turns on Spring Boot autoconfiguration. It auto-configures the beans that are present in the classpath. This simplifies the developer’s work by guessing the required beans from the classpath and configure it to run the application. This annotation is part of the spring boot project.
For example, if you have the tomcat jar file in the classpath, then Spring Boot will configure the tomcat server. As a developer, you don’t have to do anything.
Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration.
It’s a Spring Boot specific annotation. It enables the autoconfiguration of Spring ApplicationContext by:
Spring Boot provides various autoconfiguration classes in spring-boot-autoconfigure{version}.jar
, and they are typically:
@Configuration
to mark it as a Spring configuration class and@EnableConfigurationProperties
to bind the customization properties and one or more conditional bean registration methods.10. What about @SpringBootApplication?
@SpringBootApplication does 3 things:
The package of the class that is annotated with @EnableAutoConfiguration
, usually via @SpringBootApplication
, has specific significance and is often used as a ‘default’. For example, it will be used when scanning for @Entity
classes. It is generally recommended that you place @EnableAutoConfiguration
(if you’re not using @SpringBootApplication
) in a root package so that all sub-packages and classes can be searched.
It’s a top-level annotation designed to use only at class level. It’s a convenience annotation that equivalent to declaring the following three:
@EnableAutoConfiguration
: enable Spring Boot’s auto-configuration mechanism
@ComponentScan
: enable @Component scan on the package where the application is located
@Configuration
: allow to register extra beans in the context or import additional configuration classes
11. Does Spring Boot do component scanning? Where does it look by default?
Yes, Spring Boot does component scanning. Spring Boot scans all sub-packages from the root package. It also scans packages that have at least one configuration class.
@ComponentScan
or @SpringBootApplication
enables component scanning.
If no component scanning attribute defined, it will scan only the package in which the class annotated.
The base package(s) which to scan for components can be specified using the basePackages element in the @ComponentScan
annotation or by specifying one or more classes that are located in the base package(s)
@SpringBootApplication(scanBasePackageClasses = HelloWorld.class) public class OrdersDBConfig {} @Configuration @EnableAutoConfiguration @ComponentScan(basePackages = "com.mycompany.myproject") @EntityScan(basePackageClasses=Person.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
12. What is a Spring Boot starter POM? Why is it useful?
Starter POM is a set of dependencies that work as some templates for dependencies used for different tasks.
Starter POMs are that all the dependencies needed to get started with a certain technology have been gathered.
A developer can rest assured that there are no dependencies missing and that all the dependencies have versions that work well together.
All official starters follow a similar naming pattern: spring-boot-starter-*
, where *
is a particular type of application.
Spring Boot supports both Java properties and YML files. Would you recognize and understand them if you saw them?
Java properties files come in application.properties file; YAML come in application.yml
Can you control logging with Spring Boot? How?
Yes. First you add the required dependencies to the classpath and then configure the required framework using application.properties or framework-specific configuration file placed in the classpath.
Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s spring-jcl
module.
Spring Boot uses Commons Logging internally by default, but it leaves the underlying implementation open.
Default configurations are provided for
By default, if you use the “Starters”, Logback is used for logging.
By default, ERROR, WARN, and INFO level messages are logged. In application.properties
add: debug=true
to enable debug level logging.
Logging is initialized before the application context, so it is impossible to control logging from using @PropertySources
in @Configuration
classes.
System properties and conventional Spring Boot external configuration files should be used. Depending on the logging system that is used, Spring Boot will look for the specific configuration files.
The logfile name to use by default by Spring Boot can be configured using the logging.file
Spring Environment variable.
A checked exception is an exception that is caught during compile time. Usually, if you use an IDE, the IDE will show you that you have a checked exception.
An unchecked exception is an exception that is caught at runtime. It is not caught during compile time. You have to account for this type of exception and provide a way to handle it at runtime.
Exception
RuntimeException
.2. Why does Spring prefer unchecked exceptions?
SQLException
happens, nothing you can do.Spring prefers unchecked exception because this way it gives the developer possibility to choose to handle them or not – he is not enforced to handle them. To use Spring specific exceptions you must use Spring templates. JdbcTemplate takes care of transforming SQLExceptions to meaningful DataAccessExceptions, this is done using SQLExceptionTranslators.
3. What is the data access exception hierarchy?
Each data access technology has its own exception types, such as
What Spring does is to handle technology‐specific exceptions and translate them into its own exception hierarchy. The hierarchy is to isolate developers from the particulars of JDBC data access APIs from different vendors.
Spring’s DataAccessException
Spring data access exception family has three main branches:
org.springframework.dao.NonTransientDataAccessException
RecoverableDataAccessException
springframework.dao.TransientDataAccessException
.
QueryTimeoutException
is thrown. The developer can treat this exception by retrying the query.4. How do you configure a DataSource in Spring? Which bean is very useful for development/test databases?
DataSource is a generalized connection factory. It hides connection pooling and transaction management from application code. Spring obtains connections to a database through a DataSource.
With Spring you can configure different types of DataSources:
JDBC driver-based DataSources are the simples type. Spring has 3 types of them:
@Bean public DataSource datasource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("org.h2.Driver"); //this is a in-memory DB ds.setUrl("jdbc:h2:tcp://localhost/~/databaseName"); ds.setUsername("admin"); ds.setPassword("pass"); return ds; }
A very important DataSource implementation for development/testing purposes is the embedded data source. H2 is an embedded data source that is mostly used by developers for testing.
5. What is the Template design pattern and what is the JDBC template?
The Template method design pattern is about the following: you have an abstract class that has one final non-abstract method that defines some algorithm and more abstract methods that are to be implemented in the child classes. And when you run the final method (that you get from the abstract class) you get the algorithm defined in the abstract class but the implementation is done in the child non-abstract class. Meanwhile, our JdbcAccessor class that is abstract and is the parent class for JdbcTemplate has no such a method that is final and defines some algorithm.
JdbcTemplate is a convenience class that hides a lot of JDBC boilerplate code and allows to:
The Spring JdbcTemplate simplifies the use of JDBC by implementing common workflows for
Benefits are:
DataAccessException
Spring comes with three template classes to choose from:
JdbcTemplate:
JdbcTemplate works with queries that specify parameters using the '?'
placeholder.
Use queryForObject
when it is expected that execution of the query will return a single result.
Use RowMapper<T>
when each row of the ResultSet maps to a domain object.
Use RowCallbackHandler
when no value should be returned.
Use ResultSetExtractor<T>
when multiple rows in the ResultSet map to a single object.
initialize JdbcTemplate
The general practice is to initialize JdbcTemplate within the setDataSource method so that once the data source is injected by Spring, JdbcTemplate will also be initialized and ready for use.
Once configured, JdbcTemplate is thread-safe. That means you can also choose to initialize a single instance of JdbcTemplate in Spring’s configuration and have it injected into all DAO beans.
@Configuration public class DemoJdbcConfig { @Bean public DataSource dataSource() { return new DataSource(); } @Bean public JdbcTemplate jdbcTemplate(){ JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(dataSource()); return jdbcTemplate; } }
NamedParameterJdbcTemplate:
The NamedParameterJdbcTemplate
class adds support for programming JDBC statements by using named parameters, as opposed to programming JDBC statements using only classic placeholder ( '?'
) arguments.
public int countOfActorsByFirstName(String firstName) { String sql = "select count(*) from T_ACTOR where first_name = :first_name"; SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName); return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class); } //Map-based style public int countOfActorsByFirstName(String firstName) { String sql = "select count(*) from T_ACTOR where first_name = :first_name"; Map<String, String> namedParameters = Collections.singletonMap("first_name", firstName); return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class); } // BeanPropertySqlParameterSource public int countOfActors(Actor exampleActor) { String sql = "select count(*) from T_ACTOR where first_name = :firstName and last_name = :lastName"; SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor); return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class); }
6. What is a callback? What are the three JdbcTemplate callback interfaces that can be used with queries? What is each used for?
a callback is any executable code that is passed as an argument to other code, which is expected to call back(execute) the argument at a given time
public class Test { public static void main(String[] args) throws Exception { new Test().doWork(new Callback() { // implementing class @Override public void call() { System.out.println("callback called"); } }); } public void doWork(Callback callback) { System.out.println("doing work"); callback.call(); } public interface Callback { void call(); } }
JdbcTemplate 3 central callback interfaces:
Others:
7. Can you execute a plain SQL statement with the JDBC template?
Yes, using execute() methods – one of them accepts StatementCallback objects and the other wraps the String you pass in a StatementCallback. StatementCallback in its turn has a doInStatement() method that accepts Statement objects. So you can pass either an anonymous class with overridden doInStatement() method or just a simple String that execute() method of Statement will be run on.
template.execute(new StatementCallback<ResultSet>() { public ResultSet doInStatement(Statement statement) throws SQLException, DataAccessException { ResultSet rs = statement.executeQuery("SELECT * FROM databaseTable"); RowCallbackHandler handler = new RowCallbackHandler() { public void processRow(ResultSet resultSet) throws SQLException { while (resultSet.next()) { System.out.println(resultSet.getObject(1) + "," + resultSet.getObject(3)); } } }; handler.processRow(rs); return rs; } });
Yes. With following methods:
DML
DML stands for Data Manipulation Language, the commands SELECT, INSERT, UPDATE, and DELETE are database statements used to create, update, or delete data from existing tables.
DDL DDL stands for Data Definition Language, used to manipulate database objects: tables, views, cursors, etc. DDL database statements can be executed with JdbcTemplate using the execute method.
public int createTable(String name) { jdbcTemplate.execute("create table " + name + " (id integer, name varchar2)" ); String sql = "select count(*) from " + name; return jdbcTemplate.queryForObject(sql, Integer.class); }
8. When does the JDBC template acquire (and release) a connection – for every method called or once per template? Why?
9. How does the JdbcTemplate support generic queries? How does it return objects and lists/maps of objects?
10. What is a transaction? What is the difference between a local and a global transaction?
The context of execution for a group of SQL operations is called a transaction. Run them all successfully, or reverted. Tansaction enforces ACID principle.
Transactions are described in terms of ACID properties, which are as follows:
In short a local transaction is a simple transaction that is about one single database; whilst a global one is application server managed and spreads across many components/ technologies. For global transactions consider the case that a record must be persisted in a database ONLY if some message is sent to a queue and processed – if the later fail the transaction must be rolled back.
11. Is a transaction a cross-cutting concern? How is it implemented by Spring?
Yes as it can affect many components. The core concept in Spring transactions world is the transaction strategy that is defined by PlatformTransactionManager. This interface is a service provider interface. It has multiple implementations and the one you choose depends on your requirements. From PlatformTransactionManager through getTransaction() method – by passing the TransactionDefinition in, you get the TransactionStatus that may represent a new or an existing transaction.
TransactionStatus specifies:
of the transaction to be looked up in the PlatformTransactionManager.
12. How are you going to define a transaction in Spring?
Two ways of implementing it:
@transaction
TransactionTemplate
PlatformTransactionManager
Declarative transaction management is non-invasive.
@Configuration
PlatformTransactionManager
bean using @bean
@EnableTransactionManagement
@Configuration @EnableTransactionManagement public class TestDataConfig { @Bean public PlatformTransactionManager txManager(){ return new DataSourceTransactionManager(dataSource()); } }
@Transactional
@Service public class UserServiceImpl implements UserService { @Transactional(propagation = Propagation.REQUIRED, readOnly= true) @Override public User findById(Long id) { return userRepo.findById(id); } }
It is possible to use both declarative and programmatic transaction models simultaneously.
Programmatic transaction management allows you to control transactions through your codeexplicitly starting, committing, and joining them as you see fit.
Spring Framework provides two ways of implemeting Programmatic Transaction:
TransactionTemplate
, which is recommended by Spring;PlatformTransactionManager
directly, which is low level.Using TransactionTemplate
It uses a callback approach.
can write a TransactionCallback
implementation, run execute(..)
public class SimpleService implements Service {
// single TransactionTemplate shared amongst all methods in this instance
private final TransactionTemplate transactionTemplate;
// use constructor-injection to supply the PlatformTransactionManager
public SimpleService(PlatformTransactionManager transactionManager) {
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
public Object someServiceMethod() {
return transactionTemplate.execute(new TransactionCallback() {
// the code in this method executes in a transactional context
public Object doInTransaction(TransactionStatus status) {
updateOperation1();
return resultOfUpdateOperation2();
}
});
}
}
Declarative way deals with adding some AOP related to transactions to the methods annotated with @Transactional or that have some tx-advices defined by XML.
Programmatic way is about using either TransactionTemplate or directly PlatformTransactionManager.
13. What does @Transactional do? What is the PlatformTransactionManager?
General Rule: Add the @Transaction
annotation to the method that start (and finish) the unit of work. That is the part of your program that should been handled in on transaction (meaning, that it should be done/saved completely or not at all).
Rather than using XML AOP for matching the methods that should be transactional you can add this (@Transactional) annotation. PlatformTransactionManager is an interface that defines the transaction strategy through different implementations that match requirements specific to the project they are used in.
@Transactional
is metadata that specifies that an interface, class, or method must have transactional semantics.
@Transactional
Settings
The transactionManager attribute value defines the transaction manager used to manage the transaction in the context of which the annotated method is executed
The readOnly attribute should be used for transactions that involve operations that do not modify the database (example: searching, counting records). Defalt FALSE.
The propagation attribute can be used to define behavior of the target methods: if they should be executed in an existing or new transaction, or no transaction at all. There are seven propagation types. Default: PROPAGATION_REQUIRED.
The isolation attribute value defines how data modified in a transaction affects other simultaneous transactions. As a general idea, transactions should be isolated. A transaction should not be able to access changes from another uncommitted transaction. There are four levels of isolation, but every database management system supports them differently. In Spring, there are five isolation values. DEFAULT: the default isolation level of the DBMS.
timeout. By default, the value of this attribute is defined by the transaction manager provider, but it can be changed by setting a different value in the annotation: @Transactional(timeout=3600)
by milliseconds.
rollbackFor. When this type of exception is thrown during the execution of a transactional method, the transaction is rolled back. By default, i’s rolled back only when a RuntimeException or Errors is thrown. In using this attribute, the rollback can be triggered for checked exceptions as well.
noRollbackFor attribute values should be one or more exception classes, subclasses of Throwable. When this type of exception is thrown during the execution of a transactional method, the transaction is not rolled back. By default, a transaction is rolled back only when a RuntimeException is thrown. Using this attribute, rollback of a transaction can be avoided for a RuntimeException as well.
Default settings for @Transactional:
PROPAGATION_REQUIRED
.ISOLATION_DEFAULT
.read/write
, which is read only = FALSE
.Annotation driven transaction settings:
mode
spring-aspects.jar
in the classpath as well as having load-time weaving (or compiletime weaving) enabled.proxyTargetClas
order
@Transactional
Ordered.LOWEST_PRECEDE NCE
.14. Is the JDBC template able to participate in an existing transaction?
If you define a method as @Transactional and internally add some JdbcTemplate code it will run in that transaction; but JdbcTemplate itself cannot manage transactions – that is job of TransactionTemplate.
15. What is a transaction isolation level? How many do we have and how are they ordered?
Transaction isolation level is the level of one isolation of one transaction from another. Transaction level is defined from the perspective of 3 characteristics:
In Spring we have the following isolation levels:
16. What is @EnableTransactionManagement for?
The @EnableTransactionManagement annotation to be used in on @Configuration classes and enable transactional support:
@Configuration @EnableTransactionManagement public class PersistenceJPAConfig{ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){ //... } @Bean public PlatformTransactionManager transactionManager(){ JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory( entityManagerFactoryBean().getObject() ); return transactionManager; } }
Both @EnableTransactionManagement
and <tx:annotation-driven ../>
enable all infrastructure beans necessary for supporting transactional execution.
Components registered when the @EnableTransactionManagement
annotation is used are:
@Transactional
@EnableTransactionManagement
and <tx:annotation-driven/>
only looks for @Transactional
on beans in the same application context they are defined in. This means that, if you put annotation driven configuration in a WebApplicationContext
for a DispatcherServlet
it only checks for @Transactional
beans in your controllers, and not your services.
17. What does transaction propagation mean?
Transaction propagation defines whether the current transaction will be extended or not.
There is an Enum that specifies the list of all possible propagation types – org.springframework.transaction.annotation.Propagation:
REQUIRES_NEW | create a new transaction, suspend any existing one |
MANDATORY | use current transaction, throw exception if none exists |
REQUIRED | use current transaction, if non exists – create one |
SUPPORTS | use current transaction, execute non-transactionally if none exists |
NEVER | execute non-transactionally, throw exception if any transaction exists |
NOT_SUPPORTED | execute non-transactionally, suspend any existing transaction |
NESTED | if a transaction exists create a nested one in it and execute everything there, else behave like Propagation.REQUIRED |
It is to define behavior of the target methods: if they should be executed in an existing or new transaction, or no transaction at all.
Spring Propagation
enum:
Propagation.REQUIRED
: @Transactional(propagation = Propagation.REQUIRED)
UnexpectedRollbackException
.Propagation.REQUIRES_NEW
:
Propagation.NESTED
.
JDBC savepoints
are used to mark new method calls. When an exception occurs in the second method, the transaction until the last savepoint is rolled backPropagation.MANDATORY
.
Propagation.NEVER
.
Propagation.NOT_SUPPORTED
:
Propagation.SUPPORTS
.
@Service public class UserServiceImpl implements UserService { @Transactional(propagation = Propagation.REQUIRED, readOnly= true) @Override public User findById(Long id) { return userRepo.findById(id); } }
18. What happens if one @Transactional annotated method is calling another @Transactional annotated method on the same object instance?
Since transaction-management is implemented using AOP @Transactional annotation will have no effect on the method being called as no proxy is created. The same behavior is characteristic of AOP aspects.
As per the limitation of Spring AOP, a self-invocation of a proxied Spring Bean effectively bypasses the proxy, thus the second method will be excuted in the same transaction with the first.
Use @Transactional
in the service layer or the DAO/ repository layer, but not both.
The service layer is the usual choice, because service methods call multiple repository methods that need to be executed in the same transaction.
The only reason to make your repositories transactional is if you do not need a service layer at all, which is usually the case for small educational applications.
19. Where can the @Transactional annotation be used? What is a typical usage if you put it at the class level?
If you put @Transactional at class-level this is equal to annotating each method of that class.
Class level:
Method level:
Interface:
20. What does declarative transaction management mean?
For declarative transaction management:
Basically, when those specified methods are called, Spring begins a new transaction, and when the method returns without any exception it commits the transaction; otherwise, it rolls back. Hence, you don’t have to write a single line of transaction demarcation code in your method bodies.
How It Works:
The @EnableTransactionManagement
annotation activates annotation‐based declarative transaction management.
Spring Container scans managed beans’ classes for the @Transactional
annotation.
When the annotation is found, it creates a proxy that wraps your actual bean instance.
From now on, that proxy instance becomes your bean, and it’s delivered from Spring Container when requested.
Programmatic transaction management is a good idea only if:
21. What is the default rollback policy? How can you override it?
22. What is the default rollback policy in a JUnit test, when you use the
@RunWith(SpringJUnit4ClassRunner.class) in JUnit 4 or @ExtendWith(SpringExtension.class) in JUnit 5, and annotate your @Test annotated method with @Transactional?
23. Why is the term “unit of work” so important and why does JDBC AutoCommit violate this pattern?
JDBC AutoCommit will treat each individual SQL statement as a transaction. This means that if logically or from business point of view you need to make sure some statement is OK before executing another one, it would fail. Transactions are meant to solve this problem by “grouping” operations in some logical way so that you confirm to ACID principle (Atomicity, Consistency, Isolation, Durability).
setAutoCommit()
to false on a JDBC connection.
24. What does JPA stand for – what about ORM?
JPA stands for Java Persistent API. ORM stands for Object Relational Mapping.
JPA: Java Persistence API. JPA is a POJO-based persistence mechanism that draws ideas from both Hibernate and Java Data Objects (JDO) and mixes Java 5 annotations in for good measure.
ORM: Object-Relational Mapping. Mappingg a java entity to SQL database table.
Benefits of using Spring’s JPA support in your data access layer:
The first step toward using JPA with Spring is to configure an entity manager factory as a bean in the Spring application context. JPA-based applications use an implementation of EntityManagerFactory
to get an instance of an EntityManager
. The JPA specification defines two kinds of entity managers:
Application-managed
EntityManagers
are created by an EntityManagerFactory
obtained by calling the createEntityManagerFactory()
method of the PersistenceProvider.LocalEntityManagerFactoryBean
produces an application-managed EntityManagerFactory
.persistence.xml
. This file must appear in the META-INF
directory in the classpath. The purpose of the persistence.xml
file is to define one or more persistence units.@Bean public LocalEntityManagerFactoryBean entityManagerFactoryBean() { LocalEntityManagerFactoryBean emfb = new LocalEntityManagerFactoryBean(); emfb.setPersistenceUnitName("demo"); return emfb; }
Container-managed
persistence.xml
.EntityManagerFactorys
are obtained through PersistenceProvider’s createContainerEntityManagerFactory()
method.LocalContainerEntityManagerFactoryBean
produces a container-managed EntityManagerFactory
.EntityManagerFactory
or EntityManager
instances within Java EE environments.
@PersistenceUnit
annotation expresses a dependency on an EntityManagerFactory
, and@PersistenceContext
expresses a dependency on a containermanaged EntityManager
instance.@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean(); emfb.setDataSource(dataSource); emfb.setJpaVendorAdapter(jpaVendorAdapter); return emfb; }
25. What is the idea behind an ORM? What are the benefits/disadvantages or ORM?
ORM is to help map our domain or entity models into database tables. In the application level, we deal with objects and not with database operations.
Idea: Developers only work on objects and no need to care about how to maintain the relationship and how they persist.
ORM Duties:
Benefits:
DataAccessException
hierarchy.Disadvantage:
26. What is a PersistenceContext and what is an EntityManager? What is the relationship between both?
JPA has two annotations to obtain container‐managed EntityManagerFactory
or EntityManager
instances within Java EE environments.
@PersistenceUnit
annotation expresses a dependency on an EntityManagerFactory
, and@PersistenceContext
expresses a dependency on a containermanaged EntityManager
instance.@PersistenceUnit
and @PersistenceContext
Spring’s PersistenceAnnotationBeanPostProcessor
must be configured explicitly:
@Bean public PersistenceAnnotationBeanPostProcessor paPostProcessor() { return new PersistenceAnnotationBeanPostProcessor(); }
if you do use Spring’s exception translation
@Bean
public BeanPostProcessor persistenceTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@PersistenceContext
PersistenceContextType.TRANSACTION
In stateless beans, like singleton bean, it is safe to use only the PersistenceContextType.TRANSACTION value for a shared EntityManager to be created and injected into for the current activePersistenceContextType.EXTENDED
PersistenceContext It’s essentially a Cache, containing a set of domain objects/entities in which for every persistent entity there is a unique entity instance.
Persistence Unit:
a group of entity classes defined by the developer to map database records to objects that are managed by an Entity Manager, basically all classes annotated with @Entity, @MappedSuperclass, and @Embedded in an application.
persistence.xml
file under the META-INF
directory. JPA no need to specify it.EntityManager represents a PersistenceContext. The entity manager provides an API for managing a persistence context and interacting with the entities in the persistence context.
@PersistenceContext
doesn’t inject an EntityManager—at least, not exactly. Instead of giving the repository a real EntityManager, it gives a proxy to a real EntityManager. That real EntityManager either is one associated with the current transaction or, if one doesn’t exist, creates a new one.EntityManagerFactory
It has the responsibility of creating application-managed Entity Manager instances and therefore a PersistenceContext/Cache. Thread safe, shareable, represent a single datasource and persistence context.
@Repository
public class JpaUserRepo implements UserRepo {
private EntityManager entityManager;
@PersistenceContext
void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}
27. Why do you need the @Entity annotation? Where can it be placed?
28. What do you need to do in Spring if you would like to work with JPA?
Declare dependencies: ORM dependency, db driver dependency, transaction manager dependency.
@Entity
classes
@Entity
marks classes as templates for domain objects, also called entities to database tables.@Entity
annotation can be applied only at class level.@Entity
are mapped to database tables matching the class name, unless specified otherwise using the@Table
annotation.@Entity
and @Id
are mandatory for a domain class.LocalEntityManagerFactoryBean
. It produces an application-managed EntityManagerFactory.EntityManagerFactory
using JNDI, use when app ran in Java EE serverLocalContainerEntityManagerFactoryBean
Define a DataSource
bean
Define a TransactionManager
bean
@Configuration @EnableJpaRepositories @EnableTransactionManagement class ApplicationConfig { @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.HSQL).build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("com.acme.domain"); factory.setDataSource(dataSource()); return factory; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory); return txManager; } }
You must create LocalContainerEntityManagerFactoryBean
and not EntityManagerFactory
directly, since the former also participates in exception translation mechanisms in addition to creating EntityManagerFactory
.
29. Are you able to participate in a given transaction in Spring while working with JPA?
Yes you can.
The Spring JpaTransactionManager supports direct DataSource access within one and the same transaction allowing for mixing plain JDBC code that is unaware of JPA with code that use JPA.
If the Spring application is to be deployed to a JavaEE server, then JtaTransactionManager
can be used in the Spring application.
30. Which PlatformTransactionManager(s) can you use with JPA?
Implementations of PlatformTransactionManager
interface. E.g.,
DataSourceTransactionManager
: Suitable if you are only using JDBC
HibernateTransactionManager
JpaTransactionManager
:
JdoTransactionManage
JtaTransactionManager
WebLogicJtaTransactionManager
JtaTransactionManager
is used for global transactions, so that they can span multiple resources such as databases, queues etc. If the application has multiple JPA entity manager factories that are to be transactional, then a JTA transaction manager is required.
When using JPA with one single entity manager factory, the Spring Framework JpaTransactionManager
is the recommended choice. This is also the only transaction manager that is JPA entity manager factory aware.
31. What does @PersistenceContext do?
@PersistenceContext
PersistenceContext It’s essentially a Cache, containing a set of domain objects/entities in which for every persistent entity there is a unique entity instance.
32. What do you have to configure to use JPA with Spring? How does Spring Boot make this easier?
To use Spring Data components in a JPA project, a dependency on the package spring-data-jpa must be introduced.
Disable Spring Data Auto Configuration in SpringBoot:
It’s useful in testing.
Disable Using Annotation
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
Disable Using Property File
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
33. What is an “instant repository”? (hint: recall Spring Data)
A Spring Data repository is also known as a “instant” repository, because they can be created instantly by extending one of the Spring-specialized interfaces.
When a custom repository interface extends JpaRepository
, it will automatically be enriched with functionality to save entities, search them by ID, retrieve all of them from the database, delete entities, flush, etc.
By default, repositories are instantiated eagerly unless explicitly annotated with @Lazy
. LAZY is a decent choice for testing scenarios.
34. How do you define an “instant” repository? Why is it an interface not a class?
Under the hood, Spring creates a proxy object that is a fullly functioning repository bean. The repository implementation is generated at application startup time, as the Spring application context is being created.
Any additional functionality that is not provided by default can be easily implemented by defining a method skeleton and providing the desired functionality using annotations. It’s including an implementation of all 18 methods inherited from
JDBC Support typical JDBC support. You could have the DataSource injected into an initialization method, where you would create a JdbcTemplate and other data access support classes
@Repository public class JdbcMovieFinder implements MovieFinder { private JdbcTemplate jdbcTemplate; @Autowired public void init(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } }
JPA repository JPA-based repository needs access to an EntityManager.
@Repository public class JpaMovieFinder implements MovieFinder { @PersistenceContext private EntityManager entityManager; }
classic Hibernate APIs inject SessionFactory
@Repository public class HibernateMovieFinder implements MovieFinder { private SessionFactory sessionFactory; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
35. What is the naming convention for finder methods?
findBy+fieldName e.g findByEmail to find an entity by its email.
prefixes find also can be replaced with read |
get | query | stream |
private static final String QUERY_PATTERN = "find|read|get|query|stream";
are
findByXxx()` identical.count
verb, on the other hand, returns a count of matching objects, rather than the objects themselves.readSpittersByFirstnameOrLastname()
= readByFirstnameOrLastname()
readPuppiesByFirstnameOrLastname()
= readThoseThingsWeWantByFirstnameOrLastname()
Distinct
, then the generated query will be written to ensure a distinct result set.predicate
specifies the properties that will constrain the result set.
String
properties, the condition may also include IgnoringCase
or IgnoresCase
.AllIgnoringCase
or AllIgnoresCase
after all the conditions to ignore case for all conditionsAnd
or Or
first
or top
keywordsUser findFirstByOrderByLastnameAsc(); User findTopByOrderByAgeDesc(); Page<User> queryFirst10ByLastname(String lastname, Pageable pageable); Slice<User> findTop3ByLastname(String lastname, Pageable pageable); List<User> findFirst10ByLastname(String lastname, Sort sort); List<User> findTop10ByLastname(String lastname, Pageable pageable);
36. How are Spring Data repositories implemented by Spring at runtime?
For a Spring Data repository a JDK dynamic proxy is created which intercepts all calls to the repository.
The default behavior is to route calls to the default repository implementation, which in Spring Data JPA is the SimpleJpaRepository class.
37. What is @Query used for?
Spring @Query annotation is used for customizing methods of some instant repository.
@Query
allows for specifying a query to be used with a Spring Data JPA repository method.
When the name of the named parameter is the same as the name of the argument in the method annotated with @Query
, the @Param
annoation is not needed.
But if the method argument has a different name, the @Param
annotation is needed to tell Spring that the value of this argument is to be injected in the named parameter in the query.
Queries annotated to the query method take precedence over queries defined using @NamedQuery
or named queries declared in orm.xml
.
Annotation-based configuration has the advantage of not needing another cofiguration file to be edited, lowering maintenance effort.
@Query("select p from Person u where p.name like %?1%") List<Person> findAllByName(String name); @Query("select p from Person p where p.name= :n") Person findOneByName(@Param("n") String name); @Query("select p.name from Person p where p.id= :id") String findNameById(Long id);
1. What is the concept of AOP?
AOP is Aspect Oriented Programming. AOP is a type of programming that aims to help with separation of cross-cutting concerns to increase modularity; it implies declaring an aspect class that will alter the behavior of base code, by applying advices to specific join points, specified by pointcuts.
2. What problems does it solve? What two problems arise if you don’t solve a cross cutting concern via AOP?
Aims to help with separation of cross-cutting concerns to increase modularity.
Code tangling and code scattering are two issues that come together when base code needs to be executed under certain conditions. Code tangling means that the same component is injected into many others, thus leading to significant dependencies coupling components together. Code scattering means duplication, because you can do the same thing in only one way. The resulting solution is difficult to extend and to maintain, harder to understand, and a pain to debug.
3. What is a cross cutting concern?
A cross-cutting concern is a functionality that is tangled with business code, which usually cannot be separated from the business logic.
4. Name three typical cross cutting concerns.
Other examples of cross-cutting concerns
Not a cross-cutting concerns
Two popular AOP libraries
It doesn’t do anything at runtime as the classes are compiled directly with aspects.
6. What is a pointcut, a join point, an advice, an aspect, weaving?
Pointcut
– An expression that selects one or more Join Points
Join Point
– A point in the execution of a program such as a method call or exception thrown
Advice
– Code to be executed at each selected Join Point
Aspect
– A module that encapsulates pointcuts and advice
Weaving
– Technique by which aspects are combined with main code
Introduction
-Spring AOP allows to introduce new interfaces (and a corresponding application) to any object advises.
Target Object
-An object is assisted by one or more respects. Also known as the object advised.
AOP Proxy
-AOP proxy is an object used to perform the contract area. This object is created by the AOP framework. In Spring AOP proxy is part of JDK dynamic proxy or proxy CGLIB.
7. How does Spring solve (implement) a cross cutting concern?
8. Which are the limitations of the two proxy-types?
Spring will create either JDK or CGLib proxies
9. What visibility must Spring bean methods have to be proxied using Spring AOP?
For JDK proxies, only public interface method calls on the proxy can be intercepted. With CGLIB, public and protected method calls on the proxy will be intercepted, and even package-visible methods if necessary. However, common interactions through proxies should always be designed through public signatures.
10. How many advice types does Spring support. Can you name each one? What are they used for?
Advice: action taken by an aspect at a join point.
@Before
always proceed to the join point unless an execution is thrown from within the advice code
@AfterReturning
execution of a join point has completed without throwing any exceptions
@AfterThrowing
invoked after the execution of a join point that resulted in an exception being thrown
@After
method will execute after a join point execution, no matter how the execution ended (even exception happens).
@Around
Around advice can be used for all of the use-cases for AOP.11. Which two advices can you use if you would like to try and catch exceptions?
@Around
. Only around advice allows you to catch exceptions in an advice that occur during execution of a join point.
@Aspect public class Audience { @Pointcut("execution(** concert.Performance.perform(..))") public void performance() {} @Around("performance()") public void watchPerformance(ProceedingJoinPoint jp) { try { System.out.println("Taking seats"); jp.proceed(); System.out.println("CLAP CLAP CLAP!!!"); } catch (Throwable e) { System.out.println("Demanding a refund"); } } }
@AfterThrowing
. After throwing advice runs when a matched method execution exits by throwing an exception. The type Throwable is the superclass of all errors and exceptions in the Java language. So, the following advice will catch any of the errors and exceptions thrown by the join points.
@Aspect public class CalculatorLoggingAspect { @AfterThrowing( pointcut = "execution(* *.*(..))", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { log.error("An exception {} has been thrown in {}()", e, joinPoint.getSignature().getName()); } }
12. What do you have to do to enable the detection of the @Aspect annotation?
3 ways of declaring Spring AOP configuration
What does @EnableAspectJAutoProxy do?
If shown pointcut expressions, would you understand them?
For example, in the course we matched getter methods on Spring Beans, what would be the
correct pointcut expression to match both getter and setter methods?
What is the JoinPoint argument used for?
What is a ProceedingJoinPoint? When is it used?
What is dependency injection?
IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes or a mechanism such as the Service Locator pattern.
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.
what are the advantages of Dependency Injection?
What is pattern?
Design patterns represent the best practices used by experienced software developers. Imagine them as solutions to general problems that software developers face during software development. They are well established and it is very vital for you to learn about them. Why would you reinvent the wheel, when you can just use it?
There is a lot of different design patterns out there.
What is an anti-pattern?
An anti-pattern is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. Imagine it is the opposite of what the pattern means.
Is dependency injection a design pattern?
Yes. Dependency injection is a pattern.
What is an interface and what are the advantages of making use of them in Java?
Interface is very powerful to run time injection of various concrete implementations of an interface in the application. By using references to interfaces instead of their concrete implementation classes help to minimize ripple effects, as the user of interface reference doesn’t have to worry about the changes in the underlying concrete implementation. 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.
Why are they recommended for Spring beans?
When Spring beans are implementing interfaces, it is very easy to change the interface implementations. You can simply exchange entire beans by changing the Spring configuration, but you don’t have to make any changes to the code.
What is meant by “application-context?
The ApplicationContext is the central interface of the Spring framework. It provides you with access to your Spring configuration.
How are you going to create a new instance of an ApplicationContext?
ApplicationContext context = new ClassPathXmlApplicationContext("config_file.xml");
What 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
When an ApplicationContext is created several things happen:
The ApplicationContext
lets you read bean definitions and access them, as the following example shows:
// create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); // retrieve configured instance PetStoreService service = context.getBean("petStore", PetStoreService.class); // use configured instance List<String> userList = service.getUsernameList();
Scopes 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”.
Can you describe the lifecycle of a Spring Bean in an ApplicationContext?
Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of beans consist of call back methods which can be categorized broadly in two groups: Post initialization call back methods and Pre destruction call back methods
Destroy method is the method that is called when the container containing it is destroyed (closed)
Initialization method is a method that does some initialization work after all the properties of the bean were set by the container.
How are you going to create an ApplicationContext in an integration test?
It is possible to create ApplicationContext with @ContextConfiguration or @WebApplicationContext annotation.
@RunWith(SpringRunner.class) // ApplicationContext will be loaded from AppConfig and TestConfig @ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) public class MyTest { // class body... }
What is the preferred way to close an application context? Does Spring Boot do this for you?
There is no need to register a shutdown hook in a web application. Spring web-based ApplicationContext implementations already have shutdown code in place.
In a non-web application, you should register a shutdown hook with the JVM. This hook will ensure, that ApplicationContext will be closed gracefully and it calls the relevant destroy methods on singleton beans (remember, that destroy callbacks are not called on prototype-scoped beans). You can register shutdown hook via ConfigurableApplicationContext. If you are using Spring Boot, then it will register this hook automatically for you.
public class Application { public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); // add a shutdown hook for the above context... context.registerShutdownHook(); // app runs here... // main method exits, hook is called prior to the app shutting down... } }
What is an initialization method and how is it used in Spring?
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 done in different ways:
can you describe dependency injection using Java configuration?
Spring IoC container manages objects or beans. To configure and manage beans you need configuration metadata. One of the ways to create configuration metadata is by using java code. You can use @Configuration to annotate a class whose purpose is to create beans.
The @Bean annotation informs Spring container, that the method will instantiate and configure a new object to be managed by the container.
@Configuration public class AppConfig { @Bean public UserService userService() { return new UserService(); } @Bean public UserService userService(UserRepository userRepository) { // userRepository will be automatically resolved by the Spring container // it can be used for constructing UserService bean return new UserService(userRepository); } }
Note here that the bean’s name will be the same as the method name.
@Autowired private UserService userService;
If you want a different name you can change the name of the bean like this.
@Bean(name="userBean") public UserService userService() { return new UserService(); } ... @Autowired private UserService userBean;
or you can do this.
@Bean public UserService userService() { return new UserService(); } ... @Autowired @Qualifier("userService")// the name of the bean private UserService userBean; or @Resource(name="userService")// the name of the bean private UserService userBean;
can you describe dependency injection using annotations (@Component, @Autowired)?
@Component annotation is used to mark a class as a Bean. You use @Component together with @ComponentScan which scans classes within a package and provides metadata for the IoC container to create beans. @Component will set the bean name derived from the class name, but if you need to set the name explicitly you just need to supply it in the brackets like @Component(“beanName”).
@Configuration @ComponentScan(basePackages= {"bean.package"}) class AppConfig { } or @Configuration @ComponentScan(basePackageClasses={UserService.class}) class AppConfig { }
@Autowired is used to provide a reference of a bean to be used. Instead of an explicit definition of a bean dependency, it is possible to ask Spring to provide dependencies automatically. This is called auto wiring. @Autowired can be used at constructors, methods, and fields.
For auto wiring Spring does this:
@RestController public class UserController { @Autowired private UserService userService; }
Spring allows for using @Named and @ManagedBean instead of @Component. Spring also allows you to use @Inject and @Resource instead of @Autowired.
can you describe component scanning, Stereotypes, and Meta-Annotations?
Spring allows marking your class as a bean ready for component-scanning using the following annotations:
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.
Spring can automatically detect your stereotype classes and instantiate beans defined inside those classes. To allow autodetection, it is needed to add the @ComponentScan annotation on your @Configuration class.
By default, components will be searched from the package, where @ComponentScan annotation is defined. If you want to scan for the components from other packages, you can define base package with @ComponentScan(“com.springcertified”)
It is possible to create composed annotations by joining several annotations together. Such meta-annotations can simplify your code and make it more readable. As an example, here is definition of the @RequestScope annotation. As you can see, it is based on the more generic @Scope annotation:
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Scope(WebApplicationContext.SCOPE_REQUEST) public @interface RequestScope { /** * Alias for {@link Scope#proxyMode}. * <p>Defaults to {@link ScopedProxyMode#TARGET_CLASS}. */ @AliasFor(annotation = Scope.class) ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS; }
can you describe scopes for Spring beans? What is the default scope?
The scope is like a prescript, which defines the way how the bean instances are created from the bean definitions. With the Java-based configuration, it’s possible to set the bean scope with the following annotation on the bean method:
@Scope("prototype") @Bean public UserService userService() { return new UserService(); }
Basic Scopes
Additional beans for web application
Are beans lazily or eagerly instantiated by default? How do you alter this behavior?
Beans are eagerly instantiated by default. This way, Spring is able to recognize issues in the configuration very early – usually during application startup. If you want to instantiate bean lazily, you can change it with the proper configuration.
@Bean @Lazy public UserService userService() { return new UserService(); }
If you want to have all beans initialized in lazy fashion, you don’t have to specify lazy initialization for the every bean. You can alter the behavior by the configuration of the lazy initialization for all beans.
@Configuration @ComponentScan(lazyInit = true) class AppConfig { @Bean public UserService userService() { return new UserService(); } }
If you have a lazy bean instantiated within a non-lazy bean than that lazy bean will be an eager instantiated bean.
What is a property source? How would you use @PropertySource?
Property source is a set of properties. Properties are usually added to the application in the form of the standard Java property files. Spring application usually has multiple property sources registered. Some of them are registered by default, but usually every application adds own property source.
server.port=9090 # devtools spring.devtools.livereload.enabled=true spring.devtools.restart.enabled=true
To access a property value you need to use the property key. For example to get the server.port. Spring will search property sources hierarchically and returns the desired property value for server.port.
@Value("${server.port}") private int portNumber;
Property sources are searched in the following order:
@Configuration @PropertySource("classpath:app.properties") public class AppConfig { @Autowired Environment env; @Bean public UserService userService() { UserService userService = new UserService(); userService.setPort(env.getProperty("server.port")); return userService; } }
What is a BeanFactoryPostProcessor and what is it used for? When is it invoked?
BeanFactoryPostProcessor is an interface that allows for defining customizing BeanDefinitions for future beans before those beans are created. The BeanFactoryPostProcessor is a special kind of object registered in ApplicationContext . Its main purpose is to alter BeanFactory before the beans are instantiated. That means, that BeanFactoryPostProcessor operates on raw bean definitions, not on the bean instances.
Why would you define a static @Bean method?
To ensure, that it will be ready in such an early stage, you should register it via static bean method. The static method declaration will avoid the requirement to have the declaring class to be instantiated. 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 requires very early initialization and thus the must not be affected by @Autowire, @PostConstruct and @Value annotations from a @Configuration annotated class.
What is a ProperySourcesPlaceholderConfigurer used for?
The PropertySourcesPlaceholderConfigurer is Springs internal implementation of the BeanFactoryPostProcessor . Its main purpose is to resolve ${…} placeholders within bean definition property values and @Value annotations with appropriate values loaded from the property sources.
public class UserService { private int concurentUsers; @Value("${app.configuration.concurent.users}") public void setConcurentUsers(int concurentUsers) { this.concurentUsers = concurentUsers; } }
The PropertySourcesPlaceholderConfigurer iterates over all bean definitions before they are created. When property defined via ${…} is found, it is replaced by the appropriate value from the property sources. When no such property is found, an exception is thrown. 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.
What is a BeanPostProcessor and how is it different to a BeanFactoryPostProcessor? What do they do? When are they called?
What is an initialization method and how is it declared on a Spring bean?
Initialization method is a special method, which is called by the ApplicationContext during the bean initialization phase. Consider the following class. It contains a method named doInitialization , which performs custom steps we want to execute when the bean is initialized
@Bean(initMethod = "doInitialization") public void userService() { return new UserService(); } ... public UserService { public UserService() { // normal constructor } public void doInitialization() { //... perform some init steps } }
What is a destroy method, how is it declared and when is it called?
If you want to execute some cleanup code when the bean is destroyed, you can configure the so-called destroy method. Consider following class containing doCleanup method.
@Bean(destroyMethod = "doCleanup") public void userService() { return new UserService(); } ... public UserService { public UserService() { // normal constructor } public void doCleanup() { //... perform some cleanup steps } }
Note that destroy callbacks are never called on Prototype scoped beans.
Consider how you enable JSR-250 annotations like @PostConstruct and @PreDestroy? When/how will they get called?
It is possible to define initialization and destroy callbacks by using @PostConstruct and @PreDestroy annotations. Those annotations are not part of the Spring framework, but they are defined directly in Java language as part of JSR-250 specification request.
Spring recognizes those annotations with the help of the CommonAnnotationBeanPostProcessor . The purpose of this bean post processor is to find bean methods annotated with @PostConstruct and @PreDestroy annotations, and register desired callbacks within ApplicationContext.
The CommonAnnotationBeanPostProcessor will be registered automatically when component scan is turned on, or it can be added to the bean configuration manually if component scan is not used. Usage of the annotations is then pretty straightforward.
public class UserService { public UserService() {} @PostConstruct protected void initialize() { // initialization code } @PreDestroy protected void destroy() { // destroy code } }
How else can you define an initialization or destruction method for a Spring bean?
Register initialization and destroy callbacks is to implement InitializingBean and DisposableBean interfaces.
The InitializingBean interface contains a single method named afterPropertiesSet() .
public class UserService implements InitializingBean { public UserService() { @Override public void afterPropertiesSet() throws Exception { // initialization code } }
The DisposableBean interface contains a single method named destroy(). Remember, that destroy callbacks are not triggered on the prototype-scoped beans.
public class UserService implements DisposableBean { public UserService() { } @Override public void destroy() throws Exception { // destroy code } }
What does component scanning do?
Component scanning scans a package or a set of packages for classes that are annotated with @Component, @Controller, @Service and @Repository and configure those classes as beans. These beans will be added automatically to the ApplicationContext without you, the developer, having to declare them explicitly using @Bean in a @Configuration or in an XML configuration metadata file. 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:
// scan package where this class is in @Configuration @ComponentScan public class AppConfig { } // scan com.foo and com.boo packages @Configuration @ComponentScan(basePackages={"com.foo","com.boo"}) public class AppConfig { } // scan UserServiceImp.class and PaymentMethodServiceImp.class classes @ComponentScan(basePackageClasses={UserServiceImp.class, PaymentMethodServiceImp.class}) public class AppConfig { }
What 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:
What do you have to do, if you would like to inject something into a private field? How does this impact testing?
It does not matter because Spring uses reflection or setter methods to assign values to beans. So it does not matter whether you use private or public fields.
How does the @Qualifier annotation complement the use of @Autowired?
@Autowiring + @Qualifier combination is used to identify or inject a bean by name. This combination can be used but it is better to use @Resource when trying to inject by name.
@Component("staff") public Staff implements Person {} @Component("employee") public Manager implements Person {} @Component public PayrollService { @Autowired @Qualifier("employee") private final Person person; }
What 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:
Interface proxy is created by Spring itself while class proxy is generated by CGLib.
@Component @Scope(proxyMode = ScopedProxyMode.INTERFACES, scopeName = "session") public class UserServiceImp implements UserService{ }
○ What are the limitations of these proxies (per type)?
Limitation of Interface type
– Proxied class must implement interfaces
Limitation of Class type
– 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)
○ What is the power of a proxy object and where are the disadvantages?
What are the advantages of Java Config? What are the limitations?
Biggest advantage of JavaConfig is type safety or compile-time check. 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.
Search is much simpler, refactoring will be bliss. Finding a bean definition will be far easier.
XML based on configuration can quickly grow big. Yes, we can split and import but still.
What does the @Bean annotation do?
@Bean annotation is used on methods that will return beans as return types. It is used to indicate that a method produces a bean to be managed by the Spring container. Typically @Bean is used in configuration classes. Bean methods may reference other @Bean
methods in the same class by calling them directly.
@Configuration public class AppConfig { @Bean public FooService fooService() { return new FooService(fooRepository()); } @Bean public FooRepository fooRepository() { return new JdbcFooRepository(); } }
What is the default bean id if you only use @Bean? How can you override this?
In a configuration class, the name of the bean in case you use @Bean on a method will instantiate a bean with the name matching the method name.
You can override this by using the name attribute of the @Bean annotation to name your bean to a name.
@Bean(name="memberService") public UserService userService() { return new UserServiceImp(); }
Why are you not allowed to annotate a final class with @Configuration
Spring requires for subclassing classes(Spring creates dynamic proxies) annotated with @Configuration (for example to check if a bean exists before calling for its creation). But a final class cannot be extended so you cannot make a proxy of a final class.
○ How do @Configuration annotated classes support singleton beans?
○ Why can’t @Bean methods be final either?
because bean methods must be proxied and final methods can be extended.
How do you configure profiles?, What are possible use cases where they might be useful?
You use @Profile to configure beans to behave according to a particular environment. Like for example you might want to use certain endpoints in dev to short cut testing but in prod you cannot have those endpoints.
Can you use @Bean together with @Profile?
Yes you can. @Profile can be used on a configuration class or bean method.
@Configuration @Profile("dev") public class AppConfig { } .... @Profile("dev") @Bean public FooService fooService() { return new FooService(fooRepository()); }
Can you use @Component together with @Profile?
Yes you can.
@Profile("dev") @Component public class UserServiceImp implements UserService { }
How many profiles can you have?
Multiple profiles can be activated at once.
How 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:
@Component public class SomeBean{ @Value("Some title") //at property private String title; private String author; @Value("Hemingway") public setAuthor(String authorName){ this.author = authorName; } private int price; public SomeBean(@Value("14")int newprice){ // ! int value is set with quotes ! this.price = newPrice;} } }
What is @Value used for?
This annotation is used for assigning some value to a bean field. It can be used at different levels
It is not accessible in a BeanFactoryPostProcessor and BeanPostProcessor by the time it is applied using a BeanPostProcessor.
What is Spring Expression Language (SpEL for short)?
SpEL is an expression language that allows you to query and manipulate an object graph at runtime.
@Component public class UserService{ @Value("#{account.name}") private String name; } ... @Bean public Account account() { return new Account("John","john@gmail.com"); }
What is the Environment abstraction in Spring?
Environment interface represents Spring abstraction for the environment. It deals with 2 aspects of a Spring application:
For a bean to interact with environment you can either make it EnvironmentAware or autowire the Environment.
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.
What can you reference using SpEL?
SpEL can reference beans, system variables, system properties.
@Bean public PaymentMethod paymentMethod() { PaymentMethod paymentMethod = new PaymentMethod(); paymentMethod.setName("Visa"); return paymentMethod; } ... @Value("#{paymentMethod.name}") private String name;// Visa
What is the difference between $ and # in @Value expressions?
$ is used for placeholders from property files or system property files
# is used for SpEL
@Value("${springboot.profile}") //will populate field with value from properties file private String profile; @Value("#{userService.name}") // will populate field with value from otherBean bean someBeanField field private String name;