Do you use Spring in a unit test?
You don’t necessarily need spring for unit tests.
@RunWith(SpringRunner.class) @SpringBootTest public class SidecarApiNotificationApplicationTests { @Autowired UserService userService; @Test public void testLoadAllUsers() { List<User> users = userService.getAllUsers(); assertNotNull(users); } }
What type of tests typically use Spring?
How can you create a shared application context in a JUnit integration test?
Spring’s integration testing support has the following primary goals:
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.
@RunWith(SpringRunner.class) @ContextConfiguration(classes = BankConfiguration.class) public class AccountServiceJUnit4ContextTests implements ApplicationContextAware { }
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.@RunWith(SpringRunner.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?
defaultRollback
attribute of @TransactionConfiguration
.@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:
public class SimpleReviewServiceTest { private ReviewRepo reviewMockRepo = mock(ReviewRepo.class); // (1) private SimpleReviewService simpleReviewService; @Before public void setUp(){ simpleReviewService = new SimpleReviewService(); simpleReviewService.setRepo(reviewMockRepo); //(2) } @Test 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.@RunWith(MockitoJUnitRunner.class)
to initialize the mock objects.MockitoAnnotations.initMocks(this)
in the JUnit @Before
method.public class MockPetServiceTest { @InjectMocks SimplePetService simplePetService; @Mock PetRepo petRepo; @Before public void initMocks() { MockitoAnnotations.initMocks(this); } @Test p ublic void findByOwnerPositive() { Set<Pet> sample = new HashSet<>(); sample.add(new Pet()); Mockito .when(petRepo.findAllByOwner(owner)) .thenReturn(sample); Set<Pet> result = simplePetService.findAllByOwner(owner); assertEquals(result.size(), 1); } } }
Mockito in Spring Boot
@MockBean
@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.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes={KindergartenConfig.class, HighschoolConfig.class}) @ActiveProfiles("kindergarten") public class ProfilesJavaConfigTest { @Autowired 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.
@RunWith(SpringRunner.class) @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:
testCompile('org.springframework.boot:spring-boot-starter-test')
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.
@ContextConfiguration
, it uses org. springframework.boot.test.context.SpringBootContextLoader
by default.@Configuration
classes are used.org.springframework.boot.test.web.client.TestRestTemplate
bean for use in web tests that use a fully running container.@RunWith(SpringRunner.class) @SpringBootTest( 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:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
in order to tell the runner class where the bean definitions come from@Autowired
to inject beans to be tested.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:
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?
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.
@PostMapping("/signup") 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?
yes
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:
So it is very convenient for REST calls.
If you saw an example using RestTemplate would you understand what it is doing?
yes.
August 21, 20191. What are authentication and authorization? Which must come first?
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:
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:
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?
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.
/admin/**
matches any path starting with /admin
.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.
antMatchers("/secured")
matches only the exact /secured
URLmvcMatchers("/secured")
matches /secured
as well as /secured/
, /secured.html
, /secured.xyz
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/users/show/*") .hasRole("ADMIN") ... } }
@EnableWebSecurity public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages") .anyRequest().authenticated() .and() .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.MvcMatcher
can also restrict the URLs by HTTP method10. 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:
@Configuration @EnableWebSecurity @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?
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)?
○ 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:
spring‐security‐taglibs
dependency. <-- 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<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.ifAllGranted
, ifNotGranted
and ifAnyGranted
were recently deprecated in favor of access attribute. “`jspauthentication
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>
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:
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:
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?
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.
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:
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?
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:
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