Spring Reference Guide Table of Content

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


Spring Study Guide – Testing

Do you use Spring in a unit test?

You don’t necessarily need spring for unit tests.

public class SidecarApiNotificationApplicationTests {
        UserService userService;

        public void testLoadAllUsers() {

          List<User> users = userService.getAllUsers();


What type of tests typically use Spring?

  • Spring provides mock objects and testing support classes for Unit Testing.
    • Tests one unit of functionality
    • Keeps dependencies minimal
    • Isolate from the environment (including Spring)
  • Spring provides first-class support for integration testing.
    • Tests the interaction of multiple units working together
    • Integrates infrastructure like database

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

Spring’s integration testing support has the following primary goals:

  • To manage Spring IoC container caching between tests. By default, once loaded, the configured ApplicationContext is reused for each test.
  • To provide Dependency Injection of test fixture instances.
  • To provide transaction management appropriate to integration testing.
  • To supply Spring-specific base classes that assist developers in writing integration tests.

To access the Context with the TestContext Framework in JUnit, two options to access the managed application context.

1. The first option is by implementing the ApplicationContextAware interface or using @Autowired on a field of the ApplicationContext type. You can specify this in the @RunWith annotation at the class level.

 @ContextConfiguration(classes = BankConfiguration.class) 
 public class AccountServiceJUnit4ContextTests implements ApplicationContextAware { }
  • The SpringRunner class, which is an alias for SpringJUnit4ClassRunner, is a custom JUnit runner helping to load the Spring ApplicationContext by using @ContextConfiguration(classes=AppConfig.class). In JUnit, you can simply run your test with the test runner SpringRunner to have a test context manager integrated.
  • By default, the application context will be cached and reused for each test method, but if you want it to be reloaded after a particular test method, you can annotate the test method with the @DirtiesContext annotation so that the application context will be reloaded for the next test method.
  • Inject Test Fixtures with the TestContext Framework in JUnit. In JUnit, you can specify SpringRunner as your test runner without extending a support class.
  @ContextConfiguration(classes = BankConfiguration.class) 
  public class AccountServiceJUnit4ContextTests { }

2. The second option to access the managed application context is by extending the TestContext support class specific to JUnit: AbstractJUnit4SpringContextTests.

Note that if you extend this support class, you don’t need to specify SpringRunner in the @RunWith annotation because this annotation is inherited from the parent.

@ContextConfiguration(classes = BankConfiguration.class) 
 public class AccountServiceJUnit4ContextTests extends AbstractJUnit4SpringContextTests { }

When and where do you use @Transactional in testing?

  1. At method level: the annotated test method(s) will run, each in its own transaction. By default, automatically rolled back after completion of the test.You can alter this behavior by disabling the defaultRollback attribute of @TransactionConfiguration.
  2. At class level: each test method within that class hierarchy runs within a transaction.You can override this class-level rollback behavior at the method level with the @Rollback annotation, which requires a Boolean value, @Rollback(false), This is equivalent to another annotation introduced in Spring @Commit.

How are mock frameworks such as Mockito or EasyMock used?

Mockito lets you write tests by mocking the external dependencies with the desired behavior. Mock objects have the advantage over stubs in that they are created dynamically and only for the specific scenario tested.

Steps of using Mockito:

  1. Declare and create the mock
  2. Inject the mock
  3. Define the behavior of the mock
  4. Test
  5. Validate the execution
public class SimpleReviewServiceTest { 

  private ReviewRepo reviewMockRepo = mock(ReviewRepo.class); // (1)
  private SimpleReviewService simpleReviewService;
  public void setUp(){
    simpleReviewService = new SimpleReviewService();
    simpleReviewService.setRepo(reviewMockRepo); //(2)
  public void findByUserPositive() {
    User user = new User();
    Set<Review> reviewSet = new HashSet<>();
    when(reviewMockRepo.findAllForUser(user)).thenReturn(reviewSet);// (3)
    Set<Review> result = simpleReviewService.findAllByUser(user); // (4)
    assertEquals(result.size(), 1); //(5)

Mockito with Annotations

  • @Mock : Creates mock instance of the field it annotates
  • @InjectMocks has a behavior similar to the Spring IoC, because its role is to instantiate testing object instances and to try to inject fields annotated with @Mock or @Spy into private fields of the testing object.
  • Use Mockito
    • Either: @RunWith(MockitoJUnitRunner.class) to initialize the mock objects.
    • OR: MockitoAnnotations.initMocks(this) in the JUnit @Before method.
public class MockPetServiceTest {

  SimplePetService simplePetService;
  PetRepo petRepo;
  public void initMocks() { 
  @Test p
  ublic void findByOwnerPositive() { 
    Set<Pet> sample = new HashSet<>(); 
    sample.add(new Pet()); 
    Set<Pet> result = simplePetService.findAllByOwner(owner); 
    assertEquals(result.size(), 1); }

Mockito in Spring Boot


  • It is a Spring Boot annotation,
  • used to define a new Mockito mock bean or replace a Spring bean with a mock bean and inject that into their dependent beans.
  • The annotation can be used directly on test classes, on fields within your test, or on @Configuration classes and fields.
  • When used on a field, the instance of the created mock is also injected
  • Mock beans will be automatically reset after each test method.
  • If your test uses one of Spring Boot’s test annotations (such as @SpringBootTest), this feature is automatically enabled.

How is @ContextConfiguration used?

In spring-test library, @ContextConfiguration is a class-level annotation, that defines the location configuration file, which will be loaded for building up the application context for integration tests.

if @ContextConfiguration is used without any attributes defined, the default behavior of spring is to search for a file named {testClassName}-context.xml in the same location as the test class and load bean definitions from there if found.

@ContextConfiguration(classes={KindergartenConfig.class, HighschoolConfig.class}) @ActiveProfiles("kindergarten") 
public class ProfilesJavaConfigTest {

  FoodProviderService foodProviderService;

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication.

@SpringBootTest(properties = "spring.main.web-application-type=reactive") 
public class MyWebFluxTests { }

How does Spring Boot simplify writing tests?

spring-boot-starter-test pulls in the following all within test scope:

  • JUnit: De-facto standard for testing Java apps
  • JSON Path: XPath for JSON
  • AssertJ: Fluent assertion library
  • Mockito: Java mocking library
  • Hamcrest: Library of matcher objects
  • JSONassert: Assertion library for JSON
  • Spring Test and Spring Boot Test: Test libraries provided by the Spring Framework and Spring Boot.

What does @SpringBootTest do? How does it interact with @SpringBootApplication and @SpringBootConfiguration?

Spring Boot features like loading external properties and logging, are available only if you create ApplicationContext using the SpringApplication class, which you’ll typically use in your entry point class. These additional Spring Boot features won’t be available if you use @ContextConfiguration.

@SpringBootTest uses SpringApplication behind the scenes to load ApplicationContext so that all the Spring Boot features will be available.

  1. If no ContextLoader is specified with @ContextConfiguration, it uses org. springframework.boot.test.context.SpringBootContextLoader by default.
  2. Automated search for a Spring Boot configuration when nested @Configuration classes are used.
  3. Loading environment-specific properties via the properties attribute.
  4. Registering a org.springframework.boot.test.web.client.TestRestTemplate bean for use in web tests that use a fully running container.
  webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, 
  properties = {"app.port=9090"}) 
public class CtxControllerTest { }
How to define a testing class in Spring?

In order to define a test class for running in a Spring context, the following have to be done:

  1. annotate the test class with @RunWith(SpringJUnit4ClassRunner.class)
  2. annotate the class with @ContextConfiguration in order to tell the runner class where the bean definitions come from
  3. use @Autowired to inject beans to be tested.
August 21, 2019

Spring Study Guide – Rest

What does REST stand for?

REpresentational State Transfer. It is for stateless communication between a client(Web, Mobile, Server, etc) and a server.

What is a resource?

An entity, model, or data that you interact with.

What does CRUD mean?

C – create
R – read
U – update
D – delete

Is REST secure? What can you do to secure it?

REST is not secure by default. We can use Spring Security to secure our REST API.

What are safe REST operations?

Safe operations are operations that don’t change the states of your resources. These are:

  • GET
  • HEAD

What are idempotent operations? Why is idempotency important?

Idempotent operations are operations that always return the same result. Idempotency is important for understanding the limits of effect some operation has on resources.

Is REST scalable and/or interoperable?

Because of the stateless nature of REST, it is easily scalable and due to its HTTP usage, it is highly interoperable because many systems support HTTP.

Which HTTP methods does REST use?

  1. GET – for read
  2. PUT – for update/replace 
  3. POST – for create
  4. PATCH – for update/modify
  5. DELETE – for delete

What is an HttpMessageConverter?

HttpMessageConverters convert HTTP requests to objects and back from objects to HTTP responses. Spring has a list of converters that is registered by default but it is customizable – additional implementations may be plugged in.

Is REST normally stateless?

REST is stateless because according to its definition it HAS to be stateless; meaning each request must contain all the required information to interact with the server without the server needing to store some context between requests. The same can be said about authentication – each request holds the authentication info required for interacting with the server.

What does @RequestMapping do?

@RequestMapping defines a handler method or class to process HTTP calls.

Is @Controller a stereotype? Is @RestController a stereotype?

@Controller is a stereotype whilst @RestController is not and is declared in a different package.

○ What is a stereotype annotation? What does that mean?

What is the difference between @Controller and @RestController?

@Controller result is passed to a view.

@RestController result is processed by a HttpMessageConverter.

For a @Controller to act as a @RestController it has to be combined with @ResponseBody.

When do you need @ResponseBody?

@ResponseBody is required when you want a controller result to pass to a message converter rather than to a view resolver. For example, you want a JSON object instead of a view.

What does @PathVariable do?

@PathVariable gets parameters for a controller method from the URI of the request.

What are the HTTP status return codes for a successful GET, POST, PUT or DELETE operation?

200 for success

400 for error

When do you need @ResponseStatus?

@ResponseStatus will prevent DispatcherServlet from trying to find a view for the result and will set a status for the response. So when you need another form of response instead of a view you use @ResponseStatus.

Where do you need @ResponseBody? What about @RequestBody? Try not to get these muddled up!

@ResponseBody is required when you want a controller result to me passed to a message converter rather than to a view resolver.

@RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object.

public ResponseEntity<SessionDTO> signUp(@Valid @RequestBody MemberSignupCreateDTO memberCreateDTO){

If you saw example Controller code, would you understand what it is doing? Could you tell if it was annotated correctly?


Do you need Spring MVC in your classpath?

Yes. Spring MVC is the core component of REST.

What Spring Boot starter would you use for a Spring REST application?

What are the advantages of the RestTemplate?

RestTemplate is used to make HTTP Rest Calls (REST Client).
Without RestTemplate, If we want to make an HTTP call, we need to create an HttpClient, pass request and form parameters, setup accept headers and perform unmarshalling of response, all by yourself. Spring RestTemplate tries to take that pain away by abstracting all these details from you.

RestTemplate has methods specific to HTTP methods:

  2. GET
  3. HEAD
  5. POST
  6. PUT

So it is very convenient for REST calls.

If you saw an example using RestTemplate would you understand what it is doing?


August 21, 2019

Spring Study Guide – Security

1. What are authentication and authorization? Which must come first?

  • Authentication – Establishing that a principal’s credentials are valid
  • Authorization – Deciding if a principal is allowed to perform an action

Authentication comes first before Authorization because the authorization process needs a principal object with authority votes to decide the user is allowed to perform an action for the secured resource.

Authentication is the process of establishing that a principal is who they claim to be (a “principal” generally means a user, device or some other system which can perform an action in your application). Usually, a user authenticates to a system by using his username and password.

Authorization refers to the process of deciding whether a principal is allowed to perform an action within your application. To arrive at the point where an authorization decision is needed, the identity of the principal has already been established by the authentication process. For example, certain endpoints in your API can only be accessed by certain roles. When you call these endpoints with a role that does not have the privilege, the endpoint should throw an exception.

2. Is security a cross-cutting concern? How is it implemented internally?

Yes, security is a cross-cutting concern. Spring Security internally is implemented using AOP – the same way as Transactions management.

3. What is the delegating filter proxy?

DelegatingFilterProxy is the entry point for spring security. The DelegatingFilterProxy is a servlet filter and It should delegate the request to the spring managed bean that must implement the servlet Filter interface.

Delegating filter proxy is a servlet filter registered with the web container that delegates the requests to a Filter implementation on the Spring context side. That is there a 2 places servlet filters are attached to:

  1. Web container 
  2. Spring context

As of Spring Security, all requests pass through delegating filter proxy that is registered with the container and then goes to FilterChainProxy (another filter but this time on the Spring context side).

Delegating filter proxy may be declared in 2 ways:

  1. In web.xml (from WEB-INF folder)
  2. By extending AbstractSecurityWebApplicationInitializer

Delegating filter proxy will pass requests to the filter whose name is springSecurityFilterChain.

4. What is the security filter chain?

Spring Security provides a number of filters by default, and most of the time, these are enough.

Spring uses a chain of filters that is customizable by pulling in and taking out some filters as well as customizing them. This chain of filters is called the security filter chain (bean from the Spring context is called springSecurityFilterChain). Filters that build the chain are created when you enable web security.

Mandatory Filter Name Main Purpose?

  1. SecurityContextIntegrationFilter – Establishes SecurityContext and maintains between HTTP requests
  2. LogoutFilter – Clears SecurityContextHolder when logout requested
  3. UsernamePasswordAuthenticationFilter – Puts Authentication into the SecurityContext on the login request
  4. ExceptionTranslationFilter – Converts SpringSecurity exceptions into HTTP response or redirect
  5. FilterSecurityInterceptor – Authorizes web requests based on config attributes and authorities

5. What is the security context?

The security context in Spring Security includes details of the principal currently using the application. The security context is always available to methods in the same thread of execution, even if the security context is not explicitly passed around as an argument to those methods. This information includes details about the principal. Context is held in the SecurityContextHolder.

6. Why do you need the intercept-url?

<intercept-url/> from <http/> is used to define the URL for the requests that we want to have some security constraints. This tag has a pattern attribute that accepts either ant style paths or regex for matching the required resources. Access attribute accepts comma-separated roles that will be allowed to access the resource (any match will grant the access).

7. In which order do you have to write multiple intercept-url’s?

Most specific patterns must come first and most general last. When matching the specified patterns defined by element intercept-URL against an incoming request, the matching is done in the order in which the elements are declared. So the most specific patterns should come first and the most general should come last.

<intercept-url pattern='/secure/a/**' access='ROLE_A'/>
<intercept-url pattern='/secure/b/**' access='ROLE_B'/>
<intercept-url pattern='/secure/**' access='ROLE_USER'/>

8. What does the ** pattern in an antMatcher or mvcMatcher do?

antMatcher(String antPattern) Allows configuring the HttpSecurity to only be invoked when matching the provided Ant-style pattern.

  1. /admin/** matches any path starting with /admin.
  2. The antMatcher(…) method is the equivalent of the <intercept-url.../> element from XML, and equivalent methods are available to replace the configuration for the login form, logout URL configuration, and CSRF token support.

mvcMatcher(String mvcPattern) Allows configuring the HttpSecurity to only be invoked when matching the provided Spring MVC pattern. Generally mvcMatcher is more secure than an antMatcher.

  1. antMatchers("/secured") matches only the exact /secured URL
  2. mvcMatchers("/secured") matches /secured as well as /secured//secured.html/secured.xyz
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  protected void configure(HttpSecurity http) throws Exception {
      .hasRole("ADMIN") ...
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {

  protected void configure(HttpSecurity http) {

        .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
      .oauth2ResourceServer() .jwt();

9. Why is a mvcMatcher more secure than an antMatcher?

  • MvcMatcher() uses Spring MVC’s HandlerMappingIntrospector to match the path and extract variables.
  • They both implement RequestMatcher interface
  • MvcMatcher can also restrict the URLs by HTTP method

10. Does Spring Security support password hashing? What is salting?

Spring Security uses PasswordEncoder for encoding passwords. This interface has a Md5PasswordEncoder that allows for obtaining hashes of the password – that will be persisted. The problem is that there are “dictionaries” of hashes available on the internet and some hacker may just match the hash with a record from those dictionaries and gain unauthorized (from system’s point of view authorized) access. To avoid that you can add some “salt” to the pass before it is hashed. Perfectly that salt (which is some appended string) is some random value – a simpler implementation is to use the user id. 

There is an implementation of PasswordEncoder – BCryptPasswordEncoder that generates the salt automatically and thus you don’t have to bother about this.

11. Why do you need method security? What type of object is typically secured at the method level (think of its purpose, not its Java type).

If we secure only the web layer there may be a way to access the service layer in case we expose some REST endpoints. That’s why usually services are secured at the method level.

12. What do @Secured and @RolesAllowed do? What is the difference between them?

P@Secured and @RolesAllowed are the same the only difference is @RolesAllowed is a standard annotation (i.e. not only spring security) whereas @Secured is spring security only.

There are annotations used to declare some methods as secured. The difference between them is that @Secured is a Spring annotation while @RolesAllowed is a JSR250 annotation. For enabling @Secured annotation you have to set the securedEnabled attribute of @EnagleGlobalMethodSecurity to true:

@EnableGlobalMethodSecurity(securedEnabled=true) // for JSR-250 use jsr250enabled="true" 
public class SecurityConfig {

13. What do @PreAuthorized and @RolesAllowed do? What is the difference between them?

@Secured and @RolesAllowed prevent a method from being executed unless the user has the required authority. But their weakness is that they’re only able to make their decisions based on the user’s granted authorities.

With SpEL expressions guiding access decisions, far more advanced security constraints can be written.

@PreAuthorize( "(hasRole('ROLE_SPITTER') and #spittle.text.length() <= 140) or hasRole('ROLE_PREMIUM')") 
public void addSpittle(Spittle spittle) { }

○ In which security annotation are you allowed to use SpEL?

  1. @PreAuthorize
  2. @PostAuthorize
  3. @PreFilter
  4. @PostFilter

For them to be accessible you have to enable the pre-post-attribute to “enabled” in the <global-method-security/> element.

  • hasRole(role): Returns true if the current user has the specified role.
  • hasAnyRole(role1,role2): Returns true if the current user has any of the supplied roles.
  • isAnonymous(): Returns true if the current user is an anonymous user.
  • isAuthenticated(): Returns true if the user is not anonymous.
  • isFullyAuthenticated(): Returns true if the user is not an anonymous or Remember-Me user.

14. Is it enough to hide sections of my output (e.g. JSP-Page or Mustache template)?

  • You can use a special tag for hiding or not generating parts of JSP depending on the access level.
  • You can also verify the user has access to the URL and only allow accessing to the view based on the user.

○ Spring Security offers a security tag library for JSP, would you recognize it if you saw it in an example?

Spring Security Taglibs provides basic support for accessing security information.

Enable it:

  1. Add spring‐security‐taglibs dependency.
  2. Declare it in the JSP page <-- before use, need to import the taglib at the top of our JSP file: --> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> Tags
  3. Authorize Tag
    The authorize tag is used to determine whether the content written between the <sec:authorize> tags should be evaluated by the JSP. It can be used to display individual HTML elements—such as buttons—in the page, according to the granted authorities of the current user.
    • url attribute
    • ifAllGrantedifNotGranted and ifAnyGranted were recently deprecated in favor of access attribute. “`jsp
    Editors only Login“`
  4. authenticate tag is authentication The authenticate tag is used to access the contents of the current Authentication token in SecurityContext. It can be used to display information about the current user in the page. <sec:authentication property="principal.username"/> <sec:authorize access="isAuthenticated()"> Welcome Back, <sec:authentication property="name"/> </sec:authorize>

August 21, 2019

Spring Study Guide – Web Layer



MVC is an abbreviation for a design pattern. What does it stand for and what is the idea behind it?

MVC stands for Model View Controller. The idea behind MVC is that your code is organized in a way that is maintainable and readable. MVC organizes your core functions into their own specific modules.

Model – handles your domain models.

View – handles views and what clients see.

Controller – controls what clients can do and see.


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


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.

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.

What is a web application context? What extra scopes does it offer?


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.

How is an incoming request mapped to a controller and mapped to a method?


What is the difference between @RequestMapping and @GetMapping?


What is @RequestParam used for?


What are the differences between @RequestParam and @PathVariable?


What are some of the parameter types for a controller method?


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


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


What is a View and what’s the idea behind supporting different types of View?


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


What is the Model?


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


What is the purpose of the session scope?


What is the default scope in the web context?


Why are controllers testable artifacts?


What does a ViewResolver do?


August 21, 2019

Spring Study Guide – Spring Boot

What is Spring Boot?

Spring Boot is a preconfigured framework that works on top of the Spring Framework. It simplifies configuration for a Spring application by combining a group of common or related dependencies into single dependencies. Spring Boot is NOT a framework but rather, an easy way of creating stand-alone applications with little or no configurations.


Spring Boot Starters is one of the major key features or components of the Spring Boot Framework. The main responsibility of Spring Boot Starter is to combine a group of common or related dependencies into single dependencies. We need to define a lot of dependencies in our build files. It is a very tedious task for a Developer.


What are the advantages of using Spring Boot?

The most important advantage is the easy configuration of a Spring application.

  • Spring Boot Starters – sets of dependencies that help set up a “typical” application.
  • Little or no configuration and no more XML configuration
  • Decrease amount of boilerplate code
  • Spring Boot Applications can easily be integrated with Spring Security, Spring Data, Spring ORM, etc.
  • Spring Boot applications provide embedded HTTP servers such as Tomcat and Jetty to develop and test web applications easily.

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.

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.

What things affect what Spring Boot sets up?

Starters that are added to dependencies – only if @EnableAutoConfiguration or @SpringBoot application are used.

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

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

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.

What embedded containers does Spring Boot support?

  1. TomCat
  2. Jetty
  3. Undertow

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.

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.

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.

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.

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.

August 21, 2019