Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Web Layer

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.

  • Model: holds the current data and business logic.
  • View: presenting data. User interacts with view.
  • Controller: accept requests from view, issues commands to model; manipulate data from model, interacts with view.

Advantages:

  • separation of concerns
  • decoupling among MVC
  • reuse of model and controllers with different views

Spring MVC Request Life Cycle

  1. Filter: The filter applies to every request. There are several commonly used filters.
  2. Dispatcher servlet: The servlet analyzes the requests and dispatches them to the appropriate controller for processing. This is where DispatcherServlet implement Front Controller design pattern.
  3. Common services: The common services will apply to every request to provide supports including i18n, theme, and file upload. Their configuration is defined in the DispatcherServlet’s WebApplicationContext.
  4. Handler mapping: This maps incoming requests to handlers (a method within a Spring MVC controller class). Spring MVC will automatically register a HandlerMapping implementation maps handlers based on HTTP paths expressed through the @RequestMapping annotation at the type or method level within controller classes.
  5. Handler interceptor: In Spring MVC, you can register interceptors for the handlers for implementing common checking or logic. For example, a handler interceptor can check to ensure that only the handlers can be invoked during office hours.
  6. Handler exception resolver: to deal with unexpected exceptions thrown during request processing by handlers.
  7. View Resolver: Spring MVC’s ViewResolver interface supports view resolution based on a logical name returned by the controller.

2. Do you need spring-mvc.jar in your classpath or is it part of spring-core?

  • Yes, you do need this jar.
  • It’s not part of Spring Core.
  • It inclues 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:

  • receiving the initial request and handling it to the required controller 
  • checking for the required controller using handler mappings
  • receiving the model and the view name from the controller and handling that to the required view after checking for that view with the view resolver (there are various types of resolvers for different view technologies – JSP, ThymeLeaf etc.)
  • calling the view resolver

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

  • Recerives requests and delegates them to registered handlers
  • Resolve views by mapping view-names to view instances
  • Resolves exceptions

To enable Spring MVC within a web application

  1. Configuring the root WebApplicationContext
  2. Configuring the servlet filters required by Spring MVC
  3. Configuring the dispatcher servlets within the application

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.

  1. getRootConfigClasses(): A root application context of type AnnotationConfigWebApplicationContext will be created.
  2. getServletConfigClasses(): A web application context of type AnnotationConfigWebApplicationContext will be created
  3. getServletMappings(): The DispatcherServelt’s mappings (context) are specified by the array of strings returned by this method.
  4. 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 request

By 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.

  • Any class that extends AbstractAnnotationConfigDispatcherServletInitializer will automatically be used to configure DispatcherServlet and the Spring application context in the application’s servlet context.
  • This initializer create a 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:

  • /static
  • /public
  • /resources
  • /META-INF/resources

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:

  1. Defining it in XML, specifically in the web.xml of the project.
  2. Using Java – since Servlet 3.0 you can use the ServletContext.addServlet() method for registering the DispatcherServlet in ServletContext. This is Done in more ways; the one I like is extending AbstractAnnotationConfigDispatcherServletInitializer which allows you to specify the web configuration class and the root application class at one time.

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

  • It is also called RootApplicationContext.
  • In a web application, parent ApplicationContext is usually created using org.springframework.web.context.ContextLoaderListener.
  • it includes the application-level configurations such as the back-end data source, security, and service and persistence layer configuration.
  • Say, it contains all non-web beans.
  • It’s available to all servlet-level WebApplicationContexts.

Child ApplicationContext

  • It is also called the web context or the DispatcherServletContext.
  • It is created by Spring MVC DispatcherServlet.
  • Beans in the web context can access the beans in the parent context, but not conversely.

We can have two DispatcherServlet instances in an application.

  • One servlet supports the user interface (called the application servlet), and
  • the other provides services in the form of RESTful-WS to other applications (called the RESTful servlet).

DispatcherServlet can be instantiated in 2 different ways and in both it is initialized by the servlet container:

  • XML
  • Java bean

 

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

  1. WebApplicationContext has all the properties of a regular Spring application contex, given that the WebApplicationContext interface extends the ApplicationContext interface
  2. WebApplicationContext can access the Servlet Context.
  3. You can always look up the WebApplicationContext using static methods from ServletContext.

In addition to the standard Spring bean scopes singleton and prototype, there are three additional scopes available in a web application context:

  • request: each http request
  • session: each http session
  • application: per 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

  1. you implement the Controller interface
  2. or annotate your controller class with the @Controller annotation

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:

  • DispatcherServlet of the application receives the request.
  • DispatcherServlet maps the request to a method in a controller.
  • DispatcherServlet holds a list of classes implementing the HandlerMapping interface.
  • DispatcherServlet dispatches the request to the controller.
  • The method in the controller is executed.

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

  1. setting the @RequestParam annotation’s required flag to false or
  2. by declaring the argument with an java.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?

  • WebRequest
  • ServletRequest
  • ServletResponse
  • HttpSession
  • Principle
  • HttpMethod
  • Locale
  • TimeZone
  • java.io
  • HttpEntity
  • Collections, like Map<>
  • Errors
  • BindingResult
  • SessionStatus
  • UriComponentsbuilder

12. What other annotations might you use on a controller method parameter? (You can ignore
form-handling annotations for this exam)

  • @PathVariable
  • @MatrixVariable: key-value pair in url
  • @RequestParam
  • @CookieValue
  • @RequestBody
  • @RequestHeader
  • @RequestPart: “multipart/form-data”
  • @ModelAttribute
  • @SessionAttribute
  • @SessionAttributes
  • @RequestAttribute

13. What are some of the valid return types of a controller method?

  • HttpEntity
  • ResponseEntity
  • HttpHeaders
  • String
  • View
  • Map<>
  • ModelAndView
  • void
  • CompletableFuture | CompletionStage: Asynchronous

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:

  • Present model in different formats
  • Adapt view to different platforms
  • Use different view-technology

15. How is the right View chosen when it comes to the rendering phase?

View Resolution Sequence

  1. Controller returns logical view name to DispatcherServlet
  2. ViewResolvers are asked in sequence (based on their Order)
  3. If ViewResolver matches the logical view name then returns which View should be used to render the output. If not, it returns null and the chain continues to the next ViewResolver
  4. Dispatcher Servlet passes the model to the Resolved View and it renders the output
  5. If the view-name cannot be resolved, then an exception.

16. What is the Model?

  • An instance of an object that implements the Model interface from the Spring framework
  • It is a collection of key-value pairs.
  • The contents of the model represents the state of the application and contains information that will be used when rendering the view.
  • The value-objects contained in the model may also contain business logic implemented in the classes instantiated to create those objects.

17. Why do you have access to the model in your View? Where does it come from?

  • It contains information that will be used when rendering the view.
  • The model is passed as a parameter to the view when the dispatcher servlet asks the selected view to render itself as part of processing a request.

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.
  • The core view resolver provided by Spring is the 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; 
  }
}

 

 

August 21, 2019

Spring Boot

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.

SpringBootComponents

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.

spring-boot-starter-dependencies

Spring Boot is an opinionated framework that helps developers build stand-alone and production-grade Spring-based applications quickly and easily.

The primary goals of Spring Boot

  • Provide a radically faster and widely accessible getting-started experience for all Spring development.
  • Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
  • Provide a range of non-functional features that are common to large classes of projects, such as
    • embedded servers,
    • security,
    • metrics,
    • health checks,
    • externalized configuration
  • Absolutely no code generation and no requirement for XML configuration.

The key features include:

  • Spring Boot starters, easy dependency management
  • Spring Boot autoconfiguration, with sensible defaults
  • Elegant configuration management
  • Spring Boot actuator
  • Easy-to-use embedded servlet container support
  • ApplicationRunner or CommandLineRunner

ApplicationRunner or CommandLineRunner

Spring Boot allows you to execute code before your application starts. Spring Boot has the ApplicationRunner and the CommandLineRunner interfaces that expose the run methods. Both interfaces offer a single run method, which is called just before SpringApplication.run(…) completes.

CommandLineRunner exposes the public void(String... args) method

$ ./mvnw spring-boot:run -Drun.arguments="arg1,arg2"

ApplicationRunner exposes the public void run(ApplicationArguments args) method. if you want to have more control over the arguments, implement this interface.

$ ./mvnw spring-boot:run -Drun.arguments="arg1,arg2"
@SpringBootApplication 
public class SpringBootSimpleApplication implements CommandLineRunner, ApplicationRunner{

  public static void main(String[] args) throws IOException {
    SpringApplication.run(SpringBootSimpleApplication.class, args);
  }
  
  @Override 
  public void run(ApplicationArguments args) throws Exception {
    args.getNonOptionArgs()
      .forEach(file -> log.info(file)); 
  }
  
  @Override 
  public void run(String... args) throws Exception {
    for(String arg:args) {
      log.info(arg);
    } 
  }
}

2. What are the advantages of using Spring Boot?

  1. 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.

  2. Spring Boot autoconfiguration. Spring Boot configures various components automatically, by registering beans based on various criteria. The criteria can be:
    • Availability of a particular class in a classpath
    • Presence or absence of a Spring bean
    • Presence of a system property
    • Absence of a configuration file

    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.

  3. Elegant configuration management
    • Spring supports externalizing configurable properties using the @PropertySource configuration
    • Spring Boot takes it even further by using the sensible defaults and powerful type-safe property binding to bean properties
    • Spring Boot supports having deparate configuration files for different profiles without requiring much configuration.
  4. Spring Boot actuator. It provides a wide variety of such production-ready features:
    • Can view the application bean configuration details
    • Can view the application URL mappings, environment details, and configuration parameter values
    • Can view the registered health check metrics
  5. Easy-to-use embedded servlet container support.
    It creates a JAR type module and embed the servlet container in the application to be a self-contained deployment unit.

3. 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.

  • It follows the “Convention Over Configuration” approach.
  • It pre-configures Spring app by reasonable defaults.
  • It’s highly customizable

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.

  • Spring applications need complex configuration
  • Spring Boot addresses the problem by eliminating the need to manually set up the boilerplate configuration.
  • Spring Boot takes an opinionated view of the application and configures various components automatically, by registering beans based on various criteria. The criteria can be:
    • Availability of a particular class in a classpath: @ConditionalOnClass, on the other hand @ConditionalOnMissingBean
    • Presence of a system property
    • Absence of a configuration file
    • Presence or absence of a Spring bean @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.

  • A specific class is present in the classpath
  • A Spring bean of a certain type isn’t already registered in the ApplicationContext
  • A specific file exists in a location
  • A specific property value is configured in a configuration file
  • A specific system property is present/absent
  • Example:
    • @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:

  • @SpringBootAnnotation – is sum of 3 annotation: @Configuration, @EnableAutoConfiguration, @ComponentScan
  • @EnableAutoConfiguration

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.

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.

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

  1. The first thing you do is change the packaging type.
    • <packaging>war</packaging> in Maven
    • apply plugin: 'war' in Gradle
  2. you need to add spring-boot-starter-tomcat as the provided scope so that it won’t get packaged inside the WAR file.

  3. Finally, you need to provide a 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?

  • Tomcat,
  • Jetty,
  • Undertow servers.

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:

  1. scanning the classpath components and
  2. registering the beans that match various conditions.

Spring Boot provides various autoconfiguration classes in spring-boot-autoconfigure{version}.jar, and they are typically:

  1. annotated with @Configuration to mark it as a Spring configuration class and
  2. annotated with @EnableConfigurationProperties to bind the customization properties and one or more conditional bean registration methods.

10. What about @SpringBootApplication?

@SpringBootApplication does 3 things: 

  1. turns on autoconfig
  2. enables auto-scanning
  3. defines a configuration class

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:

  1. @EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism

  2. @ComponentScan: enable @Component scan on the package where the application is located

  3. @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

  • Java Util Logging,
  • Log4J2, and
  • Logback

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.

 

August 21, 2019

Spring Study Guide – Data Integration

1. What is the difference between checked and unchecked exceptions?

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.

  • Checked exceptions: Java compiler requires to handle. E.g., Exception
  • Unchecked exceptions: compiler not require to declare. E.g., RuntimeException.

2. Why does Spring prefer unchecked exceptions?

  • Checked exceptions reqires handling, result in cluttered code and unnecessary coupling.
  • Unchecked exceptions are non-recoverable exceptions, should not let developer to handle. E.g., when 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

  • SQLException for direct JDBC access,
  • HibernateException used by native Hibernate, or
  • EntityException used by JPA

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

  • It is an abstract class,
  • It is the root exception.
  • Its sub-classes are unchecked exceptions.

Spring data access exception family has three main branches:

  1. org.springframework.dao.NonTransientDataAccessException
    • non-transient exceptions,
    • which means that retrying the operation will fail unless the originating cause is fixed.
    • The most obvious example here is searching for an object that does not exist.
  2. RecoverableDataAccessException
    • when a previously failed operation might succeed if some recovery steps are performed,
    • usually closing the current connection and using a new one.
    • E.g., a temporary network hiccup
  3. springframework.dao.TransientDataAccessException.
    • transient exception,
    • which means that retrying the operation might succeed without any intervention.
    • These are concurrency or latency exceptions.
    • For example, when the database becomes unavailable because of a bad network connection in the middle of the execution of a query, an exception of type 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 defined DataSources
  • JNDI DataSources
  • Connection-pooling DataSources 

JDBC driver-based DataSources are the simples type. Spring has 3 types of them:

  1. DriverManagerDataSource
  2. SimpleDriverDataSource
  3. SingleConnectionDataSource
@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:

  • execute SQL queries
  • execute update statement
  • performs stored procedures calls
  • iterates over ResultSets
  • extracts returned parameter values

The Spring JdbcTemplate simplifies the use of JDBC by implementing common workflows for

  1. querying,
  2. updating,
  3. statement execution etc.

Benefits are:

  • Simplification: reduces boilerplate code for operations
  • Handle exceptions
  • Translates Exception from different vendors, e.g., DataAccessException
  • Avoids common mistake: release connections
  • Allows customization, it’s template design pattern
  • Thread safe

Spring comes with three template classes to choose from:

  1. JdbcTemplate
  2. NamedParameterJdbcTemplate
  3. SimpleJdbcTemplate (deprecated)

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?

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:

  • RowCallbackHandler – An interface used by JdbcTemplate for processing rows of a ResultSet on a per-row basis
  • CallableStatementCreator – One of the three central callback interfaces used by the JdbcTemplate class. This interface creates a CallableStatement given a connection, provided by the JdbcTemplate class.
  • PreparedStatementCreator – One of the two central callback interfaces used by the JdbcTemplate class. This interface creates a PreparedStatement given a connection, provided by the JdbcTemplate class.

Others:

  • ResultSetExtractor
  • BatchPreparedStatementSetter – Batch update callback interface used by the JdbcTemplate class. This interface sets values on a PreparedStatement provided by the JdbcTemplate class
  • ParameterizedPreparedStatementSetter – Parameterized callback interface used by the JdbcTemplate class for batch updates. This interface sets values on a PreparedStatement provided by the JdbcTemplate class.
  • PreparedStatementCallback – Generic callback interface for code that operates on a PreparedStatement
  • StatementCallback – Generic callback interface for code that operates on a JDBC Statement
  • CallableStatementCallback – Generic callback interface for code that operates on a CallableStatement
  • ResultSetExtractor – Callback interface used by JdbcTemplate’s query methods.
  • PreparedStatementSetter – General callback interface used by the JdbcTemplate class. This interface sets values on a PreparedStatement provided by the JdbcTemplate class.

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:

  • batchUpdate()
  • execute()
  • query()
  • queryForList()
  • queryForObject()
  • queryForRowSet()
  • update()

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?

It DOES NOT acquire connection per template. It acquire connection per method and release it after that method.

If you take a look at The execute() method :

  • picks up Connection object from connection pool / create connection.
  • create Statment object.
  • execute sql query.
  • release Connection object.

Method’s like updatequeryForObject internally call execute()

9. How does the JdbcTemplate support generic queries? How does it return objects and lists/maps of objects?

JdbcTemplate supports querying for any type of object

It has many overloaded methods for querying the database but mainly you can divide them in:

  1. query()
  2. queryForObject() – if you are expecting only one object
  3. queryForMap() – will return a map containing each column value as key(column name)/value(value itself) pairs.
  4. queryForList() – a list of above if you’re expecting more results 
  • objects – queryForObject – SingleColumnRowMapper for generic types and RowMapper for custom types
  • lists – queryForList – SingleColumnRowMapper for generic types
  • maps – queryForMap – ColumnMapRowMapper for any query

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:

  • Atomicity: All changes to data are performed as if they are a single operation. That is, all the changes are persisted, or none of them are. For example, in an application that transfers funds from one account to another, the atomicity property ensures that, if a debit is made successfully from one account, the corresponding credit is made to the other account.
  • Consistency: Data is in a consistent state when a transaction starts and when it ends. For example, in an application that transfers funds from one account to another, the consistency property ensures that the total value of funds in both the accounts is the same at the start and end of each transaction.
  • Isolatation: The intermediate state of a transaction is invisible to other transactions. As a result, transactions that run concurrently appear to be serialized. For example, in an application that transfers funds from one account to another, the isolation property ensures that another transaction sees the transferred funds in one account or the other, but not in both, nor in neither.
  • Durability: After a transaction successfully completes, changes to data persist and are not undone, even in the event of a system failure. For example, in an application that transfers funds from one account to another, the durability property ensures that the changes made to each account will not be reversed.

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:

  • isolation
  • propagation
  • propagation 
  • read-only status 

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:

  1. Declarative, use @transaction
  2. Programmatic
    • Use TransactionTemplate
    • Use PlatformTransactionManager

Declarative transaction management

Declarative transaction management is non-invasive.

  1. Configure transaction management support
    • Marked a Spring Configuration class using the @Configuration
    • Using Java Configuration, define a PlatformTransactionManager bean using @bean
    • Enable transaction management by annotate the config file with @EnableTransactionManagement
    • @Configuration
       @EnableTransactionManagement
       public class TestDataConfig {
         @Bean
         public PlatformTransactionManager txManager(){
           return new DataSourceTransactionManager(dataSource());
         }
       }
  2. Declare transactional methods using @Transactional
    @Service
    public class UserServiceImpl implements UserService {
      @Transactional(propagation = Propagation.REQUIRED, readOnly= true)
      @Override
      public User findById(Long id) {
        return userRepo.findById(id);
      }
    }

    Programmatic transaction management

    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:

    1. Using TransactionTemplate, which is recommended by Spring;
    2. Using 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 interfaceclass, or method must have transactional semantics.

@Transactional Settings

  1. The transactionManager attribute value defines the transaction manager used to manage the transaction in the context of which the annotated method is executed

  2. The readOnly attribute should be used for transactions that involve operations that do not modify the database (example: searching, counting records). Defalt FALSE.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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 setting is PROPAGATION_REQUIRED.
  • Isolation level is ISOLATION_DEFAULT.
  • Transaction is read/write, which is read only = FALSE.
  • Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported.
  • Any RuntimeException triggers rollback, and any checked Exception does not.

Annotation driven transaction settings:

  • mode
    • The default mode (proxy) processes annotated beans to be proxied by using Spring’s AOP framework.
    • The alternative mode (aspectj) instead weaves the affected classes with Spring’s AspectJ transaction aspect, modifying the target class byte code to apply to any kind of method call. AspectJ weaving requires spring-aspects.jar in the classpath as well as having load-time weaving (or compiletime weaving) enabled.
  • proxyTargetClas
    • Applies to proxy mode only.
    • If it’s false or omitted, then standard JDK interface-based proxies are created.
    • If the proxy-target-class attribute is set to true, class-based proxies are created.
  • order
    • Defines the order of the transaction advice that is applied to beans annotated with @Transactional
    • Default 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:

  1. Dirty reads – one transaction can read uncommitted data from other transaction
  2. Non-repeatable read – occurs when a second transaction reads the same row from the first transaction at different times getting different data each time because of the first transaction committing some changes or deleting the row.
  3. Phantom reads – occurs when the same search criteria is returning different data because of some other transaction interfering and deleting/adding data.

In Spring we have the following isolation levels:

  • int ISOLATION_DEFAULT = -1 – Use the default isolation level of the underlying datastore.
  • int ISOLATION_READ_UNCOMMITTED = 1 – Indicates that dirty reads, non-repeatable reads, and phantom reads can occur.
  • int ISOLATION_READ_COMMITTED = 2 – Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
  • int ISOLATION_REPEATABLE_READ = 4 – Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
  • int ISOLATION_SERIALIZABLE = 8 – Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented.

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:

  • A TransactionInterceptor: calls to @Transactional methods
  • A JDK Proxy or AspectJ advice, intercepts methods annotated with @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:

  1. Propagation.REQUIRED@Transactional(propagation = Propagation.REQUIRED)
    • Starts a new transaction if there is no transaction.
    • An existing transaction is kept and the second method call is executed within the same transaction.
    • If the second method throws an exception that causes rollback, the whole transaction rolls back. It doesn’t matter if the first transaction handles that exception or not.
    • Transaction rolls back and throws UnexpectedRollbackException.
  2. Propagation.REQUIRES_NEW:
    • always starts a new transaction regardless of whether there is already an active one.
  3. Propagation.NESTED.
    • there is only one active transaction that spans method calls.
    • only available if your persistence technology is JDBC.
    • it won’t work if you are using JPA or Hibernate.
    • 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 back
  4. Propagation.MANDATORY.
    • An error occurs if there is not an active transaction.
  5. Propagation.NEVER.
    • An error occurs if there is an active transaction in the system when the method is called.
  6. Propagation.NOT_SUPPORTED:
    • If there is an active transaction when the method is called, the active transaction is suspended until the end of the method call.
  7. Propagation.SUPPORTS.
    • current method work in a transaction if one already exists.
    • Otherwise, the method will work without any transaction.
@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.

Service layer or Repository layer

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:

  1. default for all methods of the declaring class
  2. method level transactional can override some attributes
  3. its subclasses
  4. does not apply to ancestor classes up the class hierarchy

Method level:

  1. Only Public method
  2. protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the congured transactional settings.
  3. If you need to annotate non-public methods, consider using AspectJ

Interface:

  1. this works only as you would expect it to if you use interface-based proxies
  2. recommends that you annotate only concrete classes and methods

20. What does declarative transaction management mean?

For declarative transaction management:

  1. It keeps transaction management out of business logic.
  2. Easy to configure. Use Java annotations or XML configuration files.

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:

  1. The @EnableTransactionManagement annotation activates annotation‐based declarative transaction management.

  1. Spring Container scans managed beans’ classes for the @Transactional annotation.

  2. When the annotation is found, it creates a proxy that wraps your actual bean instance.

  3. 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:

  1. Has only a small number of transactional operations. For example, if you have a web application that requires transactions only for certain update operations, you may not want to set up transactional proxies by using Spring or any other technology.
  2. Being able to set the transaction name explicitly.

21. What is the default rollback policy? How can you override it?

Any RuntimeException (unchecked exception) or Error will cause by default a rollback. Checked exceptions don’t cause a rollback

How to rollback?

Just throw any RuntimeException from a method marked as @Transactional. By default all RuntimeExceptions rollback transaction whereas checked exceptions don’t.

How to override default rollback?

You can configure this by using rollbackFor and noRollbackFor annotation parameters:

@Transactional(rollbackFor=Exception.class)

The above example will rollback transaction after throwing any exception.

@Transactional too has some parameters for changing the default behaviour:

  • rollbackFor
  • noRollbackFor
  • rollbackForClassName
  • noRollbackForClassName

Rollback without exception:

You can call the following code inside your method annotated with @Transactional

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?

Test transactions will be automatically rolled back after completion of the test.

You need to annotate test method with @Transnational for transaction.

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?

  • Test-methods will be executed in a transaction, and will roll back after completion.
  • The rollback policy of a test can be changed using the @Rollback set to false, @Rollback(false)
  • @Commit indicates that the transaction for a transactional test method should be committed after the test method has completed. You can use @Commit as a direct replacement for @Rollback(false) to more explicitly convey the intent of the code. Analogous to @Rollback, @Commit can also be declared as a class-level or method-level annotation.

The @DataJpaTest tests are transactional and rolled back at the end of each test by default. You can disable this default rollback behavior for a single test or for an entire test class by annotating with @Transactional(propagation = Propagation.NOT_SUPPORTED).


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). 

  • The unit of work describes the atomicity of transactions.
  • JDBC AutoCommit will cause each individual SQL statement as to be executed in its own transaction, which makes it impossible to perform operations that consist of multiple SQL statements as a unit of work.
  • JDBC AutoCommit can be disabled by calling the 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:

  • Easier and more powerful persistence unit configuration
  • Automatic EntityManager management
  • Easier testing
  • Common data access exceptions
  • Integrated transaction management

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

  • the application is responsible for opening or closing entity managers and involving the entity manager in transactions.
  • most appropriate for use in standalone applications that don’t run in a Java EE container.
  • EntityManagers are created by an EntityManagerFactory obtained by calling the createEntityManagerFactory() method of the PersistenceProvider.
  • If you’re using an application-managed entity manager, Spring plays the role of an application and transparently deals with the EntityManager on your behalf.
  • LocalEntityManagerFactoryBean produces an application-managed EntityManagerFactory.
  • Application-managed entity-manager factories derive most of their configuration information from a configuration file called 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

  • Entity managers are created and managed by a Java EE container.
  • The application doesn’t interact with the entity manager factory at all.
  • Instead, entity managers are obtained directly through injection or from JNDI.
  • The container is responsible for configuring the entity manager factories.
  • most appropriate for use by a Java EE container that wants to maintain some control over JPA configuration beyond what’s specified in persistence.xml.
  • EntityManagerFactorys are obtained through PersistenceProvider’s createContainerEntityManagerFactory() method.
  • Spring plays the role of the container.
  • LocalContainerEntityManagerFactoryBean produces a container-managed EntityManagerFactory.
  • Instead of configuring data-source details in persistence.xml, you can configure this information in the Spring application context.
  • JPA has two annotations to obtain container‐managed EntityManagerFactory or EntityManager instances within Java EE environments.
    1. The @PersistenceUnit annotation expresses a dependency on an EntityManagerFactory, and
    2. @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:

  • Data type convertion
  • Maintaining relations between objects
  • JAP Query language to handle vendor spedific SQL

Benefits:

  • Easier testing. It’s easier to test each piece of persistence-related code in isolation.
  • Common data access exceptions. In DataAccessException hierarchy.
  • General resource management. Spring offers effcient, easy, and safe handling of persistence resources. E.g., Spring makes it easy to create and bind a Session to the current thread transparently, by exposing a current Session through the Hibernate SessionFactory .
  • Integrated transaction management. Declarative, aspect-oriented programming (AOP) style method interceptor.
  • Keep track of changes
  • Reduce code (and develop time)
  • Lazy loading. As object graphs become more complex, you sometimes don’t want to fetch entire relationships immediately.
  • Eager fetching. Eager fetching allows you to grab an entire object graph in one query.
  • Cascading. Sometimes changes to a database table should result in changes to other tables as well
  • Save you literally thousands of lines of code and hours of development time.
  • Lets you switch your focus from writing error-prone SQL code to addressing your application’s requirements.

Disadvantage:

  • Generated SQL Query low performance
  • Complexity, requires more knowledge
  • Deal with legacy database is difficult

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.

  1. The @PersistenceUnit annotation expresses a dependency on an EntityManagerFactory, and
  2. @PersistenceContext expresses a dependency on a containermanaged EntityManager instance.

@PersistenceUnit and @PersistenceContext

  • They aren’t Spring annotations; they’re provided by the JPA specification.
  • Both annotations can be used at either the field or method level.
  • Visibility of those fields and methods doesn’t matter.
  • 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

    • Used for entity manager injection.
    • Expresses a dependency on a container-managed EntityManager and its associated persistence context.
    • This field does not need to be autowired, since this annotation is picked up by an infrastructure Spring bean postprocessor bean that makes sure to create and inject an EntityManager instance.
    • @PersistenceContext has a type attribute
      • 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 active
      • PersistenceContextType.EXTENDED
        • is purposefully designed to support beans, like stateful EJBs, session Spring beans, or request‐scoped Spring beans. The shared EntityManager instance wouldn’t be bound to the active transaction and might span more than one transaction.

    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.

    • Default persistence context duration is one single transaction
    • Can be configured
    • the persistence context itself is managed by EntityManager

    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.

    • All entity classes must define a primary key, must have a non-arg constructor or not allowed to be final.
    • This set of entity classes represents data contained in a single datasource.
    • Multiple persistence units can be defined within the same application.
    • Configuration of persistence units can be done using XML, e.g., 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.

    • It does creation, update, querying, deletion.
    • An EntityManager isn’t thread-safe and generally shouldn’t be injected into a shared singleton bean like your repository. @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?

  1. Declare dependencies: ORM dependency, db driver dependency, transaction manager dependency.

  2. @Entity classes
    • is part of the javax.persistence.*, not JPA!
    • @Entity marks classes as templates for domain objects, also called entities to database tables.
    • The @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.
  3. Define an EntityManagerFactory bean.
    • Simplest: LocalEntityManagerFactoryBean. It produces an application-managed EntityManagerFactory.
    • Obtain an EntityManagerFactory using JNDI, use when app ran in Java EE server
    • Full JPA capabilities: LocalContainerEntityManagerFactoryBean
  4. Define a DataSource bean

  5. Define a TransactionManager bean

  6. Implement repositories
@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.,

  1. DataSourceTransactionManager: Suitable if you are only using JDBC

  2. HibernateTransactionManager
    • Hibernate without JPA
    • Also possible to use JDBC at the same time
  3. JpaTransactionManager:
    • Suitable if you are using JPA.
    • Also possible to use JDBC at the same time
  4. JdoTransactionManage
    • using JDO
    • Also possible to use JDBC at the same time
  5. JtaTransactionManager
    • Suitable if you are using global transactions—that is, the distributed transaction management capability of your application server.
    • You can use any data access technology
  6. 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

  • Used for entity manager injection.
  • Expresses a dependency on a container-managed EntityManager and its associated persistence context.
  • This field does not need to be autowired, since this annotation is picked up by an infrastructure Spring bean postprocessor bean that makes sure to create and inject an EntityManager instance.
  • @PersistenceContext has a type attribute
    • 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 active
    • PersistenceContextType.EXTENDED
      • is purposefully designed to support beans, like stateful EJBs, session Spring beans, or request‐scoped Spring beans. The shared EntityManager instance wouldn’t be bound to the active transaction and might span more than one transaction.

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.

  • Default persistence context duration is one single transaction
  • Can be configured
  • the persistence context itself is managed by EntityManager

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.

JPA in SpringBoot

  1. SpringBoot provides a default set fo dependencies needed for JPA in starter.
  2. Provides all default Spring beans needed to use JPA.
  3. Provides a number of default properties related to persistence and JPA.

Disable Spring Data Auto Configuration in SpringBoot:

It’s useful in testing.

  1. Disable Using Annotation

    @SpringBootApplication(exclude = {
      DataSourceAutoConfiguration.class,
      DataSourceTransactionManagerAutoConfiguration.class,
      HibernateJpaAutoConfiguration.class})

     

  2. 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)

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

  • JpaRepository,
  • PagingAndSortingRepository, and
  • CrudRepository.

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.

  1. verbs in the method name: get, read, find, query,stream and count.
    • prefixes find also can be replaced with read get query stream
        private static final String QUERY_PATTERN = "find|read|get|query|stream";
      
    • findAllByXxx() are findByXxx()` identical.
    • The count verb, on the other hand, returns a count of matching objects, rather than the objects themselves.
  2. The subject of a repository method is optional.
    • readSpittersByFirstnameOrLastname() = readByFirstnameOrLastname()
    • readPuppiesByFirstnameOrLastname() = readThoseThingsWeWantByFirstnameOrLastname()
    • They’re all requal! Beccause the type of object being retrieved is determined by how you parameterize the JpaRepository interface, not the subject of the method name.
    • There is one exception to the subject being ignored. If the subject starts with the word Distinct, then the generated query will be written to ensure a distinct result set.
  3. The predicate specifies the properties that will constrain the result set.
    • Each condition must reference a property and may also specify a comparison operation.
    • If the comparison operator is left off, it’s implied to be an equals operation.
    • You may choose any other comparison operations,
    • When dealing with String properties, the condition may also include IgnoringCase or IgnoresCase.
    • you may also use AllIgnoringCase or AllIgnoresCase after all the conditions to ignore case for all conditions
    • conditional parts are separated by either And or Or
  4. Limiting Query Results
    • The results of query methods can be limited by using the first or top keywords
    • An optional numeric value can be appended to top or first to specify the maximum result size to be returned.
    • If the number is left out, a result size of 1 is assumed.
User 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);

 

August 21, 2019

AOP

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.

  1. Avoid tangling: mixing business logic and cross cutting concerns
  2. Avoid scattering: code duplication in several modules

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? 

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.

  • Auditing
  • Security
  • Transaction management

Other examples of cross-cutting concerns

  • Logging
  • Caching
  • Internationalization
  • Error detection and correction
  • Memory management
  • Performance monitoring
  • Measuring statistics
  • Synchronization

Not a cross-cutting concerns

  • connecting to the database


Two popular AOP libraries

  1. AspectJ is the original AOP technology which aims to provide complete AOP solution. More robust, more complicated. It uses three different types of weaving:
    1. Compile-time weaving
    2. Post-compile weaving
    3. Load-time weaving

    It doesn’t do anything at runtime as the classes are compiled directly with aspects.

  2. Spring AOP aims to provide a simple AOP implementation across Spring IoC to solve the most common problems that programmers face. It makes use of only runtime weaving.
    1. JDK dynamic proxy, preferred
    2. CGLIB proxy


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?

  • Implement your mainline application logic
    • – Focusing on the core problem
  • Write aspects to implement your cross-cutting concerns
    • – Spring provides many aspects out-of-the-box
  • Weave the aspects into your application
    • – Adding the cross-cutting behaviors to the right places

8. Which are the limitations of the two proxy-types?

Spring will create either JDK or CGLib proxies

  1. JDK Proxy
    1. Also called dynamic proxies
    2. API is built into the JDK
    3. Requirements: Java interface(s)
    4. All interfaces proxied
  2. CGLib Proxy
    1. NOT built into JDK
    2. Included in Spring jars
    3. Used when interface not available
    4. Cannot be applied to final classes or methods

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.

  1. Before advice@Before always proceed to the join point unless an execution is thrown from within the advice code
    • Access control, security
    • Statistics
  2. After returning advice@AfterReturning execution of a join point has completed without throwing any exceptions
    • statistics
    • Data validation
  3. After throwing advice@AfterThrowing invoked after the execution of a join point that resulted in an exception being thrown
    • Error handling
    • Sending alerts when an error has occurred.
    • Attempt error recovery
  4. After (finally) advice@After method will execute after a join point execution, no matter how the execution ended (even exception happens).
    • Releasing resources
  5. Around@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

  • the ProxyFactoryBean,
  • the aop namespace,
  • and @AspectJ-style annotations.

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?

 

 

 

August 21, 2019

Core Spring

 

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?

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

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.

  • Creational patterns – Singleton, Prototype, Builder…
  • Structural patterns – Proxy, Facade, Decorator…
  • Behavioral patterns – Command, Observer, Template method…

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

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

When an ApplicationContext is created several things happen:

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

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”. 

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

Can you describe the lifecycle of a Spring Bean in an ApplicationContext?

Spring Bean Life Cycle

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.

Image result for bean lifecycle in spring

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:

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

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:

  • Spring tries to resolve candidates by the type first.
  • If multiple candidates exist, Spring tries to resolve the dependency by its name
  • If multiple candidates are found, and Spring cannot decide which should be used, an exception is thrown
  • If no candidates are found, an exception is thrown
  • It is possible to auto-wire beans collection of the given type
  • If ambiguity exists, we can specify autowire candidate by the @Qualifier or @Primary annotation
  • It is possible to use Java 8 Optional for optional dependencies
@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:

  1. @Component – most generic stereotype annotation. Other annotations are specializations of the @Component annotation. Use it, when more specific annotation does not fit for your purpose.
  2. @Service – marks a class as a member of the service layer.
  3. @Repository – for beans that represent a DAO. It marks a class as a member of the repository layer. All exception thrown from this class will be wrapped and translated to the Springs
  4. @Controller – marks a class as an annotated controller. Methods of such class will be used for handling of the incoming http requests.

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

  1. singleton – the default scope for the beans. Will ensure that only one instance of the bean will be created per current IoC container (Spring container). Used for stateless beans.
  2. prototype – any number of bean instances may be created. Used for stateful beans. For this type of beans configured destruction lifecycle callbacks are not called. User must clean up this type of objects and release the resources that they are holding; usually using custom bean post-processor for that.

Additional beans for web application

  1. request – a bean instance will be created per each HTTP request. @RequestScope may be used with @Component to assign this scope.
  2. session – one instance per HTTP Session lifecycle. @SessionScope may be used with @Component to assign this scope.
  3. globalSession – one instance per HTTP global Session. Usually only valid when used in a Portlet context
  4. application – one instance per ServletContext. @ApplicationScope may be used with @Component to assign this scope.
  5. websocket – one instance per WebSocket

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:

  1. ServletConfig parameters (if applicable — for example, in case of a DispatcherServlet context)
  2. ServletContext parameters (web.xml context-param entries)
  3. JNDI environment variables (java:comp/env/ entries)
  4. JVM system properties (-D command-line arguments)
  5. JVM system environment (operating system environment variables)
  6. You can also add your own property file using @PropertySource.
@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:

  1. @Primary annotation to identify a “preferable” bean among different implementations of an interface
  2. @Qualifier annotation to indicate directly the preferred bean.

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:

  1. Interface proxy(created by Spring itself)
  2. Class proxy(generated by CGLib)

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:

  • for Java-based configurations: use @Value annotation at constructor arguments, over properties and at setter methods
  • for XML-based configurations: c-namespace for constructors and p-namespace for properties
@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

  • constructor
  • setter
  • field

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:

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

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

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;

 

August 21, 2019