0% found this document useful (0 votes)
5 views22 pages

Spring Data MCQs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

Spring Data MCQs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Spring Data MCQs

1. Which statement about Spring Data repository interfaces is true?


A. CrudRepository extends JpaRepository
B. JpaRepository extends PagingAndSortingRepository and adds JPA-specific methods like
flush() 1

C. PagingAndSortingRepository is the parent of CrudRepository


D. JpaRepository does not support pagination or sorting

Answer: B
Explanation: JpaRepository extends PagingAndSortingRepository (which in turn extends
CrudRepository ) and adds JPA-specific methods such as flush() , saveAndFlush() , and overrides
for saveAll() to return a List 1 .

1. Which Spring Data interface provides built-in methods for pagination and sorting?
A. CrudRepository
B. Repository
C. PagingAndSortingRepository 2

D. JpaRepository

Answer: C
Explanation: PagingAndSortingRepository is specifically designed to include pagination and sorting
abstractions (e.g. findAll(Pageable) and findAll(Sort) ) 2 .

1. What do the keywords First and Top do in a Spring Data JPA query method name?
A. They must be accompanied by a numeric value.
B. They are synonyms; without a number they default to 1 3 .
C. First sorts ascending, Top sorts descending.
D. They limit results to 100 by default.

Answer: B
Explanation: In Spring Data JPA query derivation, First and Top are interchangeable keywords for
limiting results. If no numeric value is appended (e.g. findFirstBy ), they default to returning one record
3 .

1. Which annotation is used to define a custom JPQL query on a repository method?


A. @Query 4
B. @NativeQuery
C. @NamedQuery
D. @CustomQuery

Answer: A
Explanation: To specify a custom JPQL (or SQL) query on a Spring Data repository method, you use the

1
@Query annotation on the method. This allows you to provide the JPQL directly in the repository interface
4 .

1. If you annotate an entity with @NamedQuery(name="User.findByEmail", ...) and have a


repository method findByEmail(String email) , what happens?
A. The @NamedQuery is ignored.
B. The named query User.findByEmail is used automatically 5 .
C. An error is thrown for ambiguity.
D. Spring Data will generate a dynamic query instead.

Answer: B
Explanation: Spring Data JPA will look for a named query matching the domain class and method name
(e.g. User.findByEmail ). If such a named query exists, it will be used instead of deriving a query from
the method name 5 .

1. By default, what transaction settings do Spring Data JPA CrudRepository methods use?
A. Read operations are non-transactional, writes are REQUIRES_NEW .
B. Read operations have readOnly=true , other methods use default @Transactional 6 .
C. All methods default to readOnly=false .
D. Methods are transactional only if annotated manually.

Answer: B
Explanation: By default, Spring Data JPA methods inherited from CrudRepository have transactional
settings from SimpleJpaRepository : read operations run with readOnly=true , and save/delete
operations run with a standard @Transactional (no readOnly flag) 6 .

1. Are custom query methods (e.g. using @Query ) in Spring Data JPA transactional by default?
A. Yes, all repository methods are always transactional.
B. No, they have no transaction settings unless annotated. 7

C. Yes, and always readOnly=true .


D. Yes, but only for delete/modify queries.

Answer: B
Explanation: Declared query methods (including those with @Query ) do not inherit transactional settings
by default. If you need them to be transactional, you must annotate them (or their repository) with
@Transactional explicitly 7 .

1. Which return types can be used for a repository method that accepts a Pageable argument?
A. Only Page<T>
B. Page<T> , Slice<T> , or List<T> 8

C. Only List<T>
D. Any Iterable<T>

Answer: B
Explanation: When using a Pageable parameter, Spring Data JPA methods can return Page<T> ,

2
Slice<T> , or a List<T> . A Page will trigger an extra count query to determine total elements,
whereas Slice and List do not 8 .

1. What is the key difference between Page<T> and Slice<T> in Spring Data pagination?
A. Page does not include pagination info, Slice does.
B. Page triggers a count query for total elements; Slice does not 9 .
C. Slice always reads the entire table.
D. There is no difference; they are synonyms.

Answer: B
Explanation: A Page<T> knows the total number of elements and pages (requiring a count query),
whereas a Slice<T> only knows if there is a next slice available and does not execute a count query 9 .

1. What effect does the keyword Distinct have in a Spring Data JPA method name?
A. It causes an error unless @Query is used.
B. It adds SELECT DISTINCT to the query, ensuring unique results 10 .
C. It returns a Set<T> instead of a List<T> .
D. It de-duplicates results in memory after fetching.

Answer: B
Explanation: Using Distinct in a method name (e.g. findDistinctByX ) causes Spring Data
JPA to use a SELECT DISTINCT in the query, thereby returning unique root entities. Note that the
semantics depend on entity definitions as explained in the documentation 10 .

2. How can you override the default transaction attributes for a Spring Data JPA repository
method?
A. Configure it in application.properties .
B. Declare the method again in the repository and annotate it (e.g.
@Transactional(timeout=10) ) 11 .
C. Use @Transactional only on service layer.
D. Default attributes cannot be changed.

Answer: B
Explanation: To customize transaction settings (e.g. timeout or isolation) for a specific CRUD
method, you redeclare it in your repository interface and add the desired @Transactional
attributes. For example, overriding findAll() with @Transactional(timeout=10) will apply
that timeout 11 .

3. In Spring Data JPA, how do you add a custom method implementation to a repository?
A. Annotate the repository interface with @CustomRepository .
B. Define a separate interface and an implementation class with Impl suffix 12 .
C. Extend JdbcRepository .
D. Put the method in the repository interface and Spring will auto-implement it.

Answer: B
Explanation: To add custom behavior, define a fragment interface (e.g.

3
CustomizedUserRepository ) and provide a class with the same name plus Impl (e.g.
CustomizedUserRepositoryImpl ) 12 . Then let your main repository interface extend this
fragment interface; Spring Data will detect and wire in the implementation.

4. Which Spring Data JPA interface should a repository extend to support JPA Specifications
(Criteria API predicates)?
A. JpaSpecificationExecutor 13
B. QueryByExampleExecutor
C. QueryDslPredicateExecutor
D. JdbcRepository

Answer: A
Explanation: To use JPA Specification<T> (the Criteria API approach) with a repository, extend
JpaSpecificationExecutor<T> in your repository interface 13 . This provides methods like
findAll(Specification) , allowing composition of criteria predicates.

5. Which interface should a Spring Data repository extend to support Query by Example?
A. JpaRepository
B. QueryByExampleExecutor<T> 14

C. JpaSpecificationExecutor<T>
D. ExampleRepository

Answer: B
Explanation: For Query by Example functionality, the repository needs to extend
QueryByExampleExecutor<T> in addition to a standard repository interface. This provides
methods like findAll(Example<S>) 14 .

6. In Spring Data JPA Query by Example, which fields are ignored by default in the example
(probe) object?
A. Primitive type fields (int, double, etc.)
B. Fields annotated with @Ignore
C. All non-null fields
D. Fields with null values 15

Answer: D
Explanation: By default, Query by Example ignores properties that have null values in the probe
entity. Only non-null fields are included in the matching criteria 15 .

7. Which interface must be extended to use Querydsl with Spring Data JPA repositories?
A. JpaRepository
B. JpaSpecificationExecutor
C. QueryDslPredicateExecutor 16

D. QuerydslJpaRepository

Answer: C
Explanation: To enable Querydsl predicate support, your repository should extend

4
QueryDslPredicateExecutor<T> . This allows using Querydsl BooleanExpression objects in
methods like findAll(...) 16 .

8. What does calling saveAndFlush() on a Spring Data JPA repository do?


A. Saves the entity but does not commit the transaction.
B. Saves the entity and immediately flushes changes to the database.
C. Saves the entity and clears the persistence context.
D. Only flushes without saving.

Answer: B
Explanation: The saveAndFlush() method (provided by JpaRepository ) saves the entity and
then immediately calls flush() on the EntityManager , forcing the SQL INSERT/UPDATE to be
executed in the database.

9. What does existsByX(...) return when a matching record is found?


A. The entity instance.
B. A boolean true if at least one matching record exists.
C. The count of matching records.
D. An Optional .

Answer: B
Explanation: Methods starting with existsBy... in Spring Data return a boolean . It will be
true if a matching record is found, false otherwise (essentially checking if count > 0).

10. How can you define pagination in a query method without using an @Query annotation?
A. Use findAll(Pageable pageable) .
B. Just declare any method, Spring paginates automatically.
C. Provide a Pageable parameter and return type Page<T> (or Slice<T> / List<T> ).
D. It’s not possible without @Query .

Answer: C
Explanation: You can add a Pageable parameter to the method signature and use return type
Page<T> , Slice<T> , or List<T> . Spring Data JPA will apply pagination to the query
automatically. (E.g. Page<User> findByStatus(String status, Pageable page) .)

11. What annotation allows named parameters in @Query methods and how are they used?
A. @NamedParam on the method
B. @Param("name") on each method argument and use :name in JPQL 17

C. No annotation needed, Spring matches by variable name


D. @QueryParam("name")

Answer: B
Explanation: When using named parameters in an @Query string, each corresponding method
parameter should be annotated with @Param("paramName") . The JPQL should use :paramName .
For example: @Query("select u from User u where u.firstname = :firstname") User
findByFirstname(@Param("firstname") String fname) 17 .

5
12. Which of the following is a valid Spring Data JPA derived query method name?
A. findUsersByAgeGtAndName(String name, int age)
B. getByAddress_City(String city)
C. fetchByEmailLikeOrUsernameContains(String username, String email)
D. selectByDateBefore(LocalDate date)

Answer: B
Explanation: find , get , query are all valid prefixes ( findBy , getBy , etc.). Underscores can
navigate nested properties (as in Address_City ). The rest must match property names and
keywords ( Like , Contains ). selectByDateBefore is invalid because it uses selectBy
which is not a supported prefix.

13. What happens if a query method that is supposed to return one entity finds no results?
A. Returns null .
B. Throws EmptyResultDataAccessException .
C. Returns an Optional.empty() if declared as Optional<T> , otherwise null .
D. Returns an empty list.

Answer: C
Explanation: If a repository method returns a domain type (not a collection) and finds no result, it
returns null . If the return type is Optional<T> , then it returns Optional.empty() . (Using
Optional<T> is the recommended approach to handle no-result cases.)

14. Which repository return type can cause Spring Data to issue an automatic count query?
A. List<T>
B. Page<T> 9

C. Slice<T>
D. Stream<T>

Answer: B
Explanation: A Page<T> return type triggers Spring Data to run a count query to determine the
total number of elements (for pagination calculations) 9 . Slice<T> and List<T> do not cause
such an extra query.

15. How do you customize a repository’s findAll() method to run non-read-only (e.g. with
timeout)?
A. Override the findAll() method in a custom base class.
B. Redeclare findAll() in the repository interface with @Transactional(timeout=...) 11 .
C. It cannot be customized; use a service layer.
D. Use XML config.

Answer: B
Explanation: You can redeclare an inherited method (like findAll() ) in the repository interface
and annotate it with your desired transactional attributes. For instance:

6
@Override
@Transactional(timeout = 10)
List<User> findAll();

This causes findAll() to run with a 10-second timeout instead of the default 11 .

16. In derived query methods, how can you compare a date range?
A. findByDateRange(LocalDate start, LocalDate end)
B. findByDateBetween(LocalDate start, LocalDate end)
C. findByDateGtAndDateLt(LocalDate start, LocalDate end)
D. findByDateIn(LocalDate start, LocalDate end)

Answer: B
Explanation: To query a range of dates, use the Between keyword: e.g.
findByDateBetween(LocalDate start, LocalDate end) . Spring Data understands
Between and generates a query where date BETWEEN ? AND ? .

17. What is the result of a deleteBy derived method when no records match the criteria?
A. It throws an exception.
B. It does nothing (no error).
C. It deletes all records (inverted logic).
D. It returns false .

Answer: B
Explanation: Derived delete methods (like deleteByStatus(String status) ) issue a delete
operation with the given criteria. If no records match, nothing happens (no exception) – it simply
affects zero rows.

18. Which keyword in a method name would make a query sorted by a given property?
A. SortBy
B. OrderBy 18

C. Sorted
D. SortedBy

Answer: B
Explanation: Use OrderBy followed by the property name (e.g.
findByLastnameOrderByFirstnameDesc(String lastname) ). Spring Data supports
OrderBy to append an ORDER BY clause to the query 18 .

19. How would you retrieve just the first 5 results in descending order of salary for
findByName(String name) ?
A. findTop5ByName(String name) then sort in code.
B. findTop5ByNameOrderBySalaryDesc(String name) 3 .
C. findByName(String name, Sort.by("salary", DESC)) .
D. Set a page request of size 5 and sort.

7
Answer: B
Explanation: The method findTop5ByNameOrderBySalaryDesc(String name) tells Spring
Data to limit to 5 results and sort them by salary descending. (Option D also works in practice, but
the question asks for a single method name solution). Using Top5 and OrderBySalaryDesc is
the conventional approach 3 .

20. What does the keyword ExistsBy do in a repository method name?


A. Returns a boolean indicating if at least one record matches the criteria.
B. Returns the first matching entity.
C. Throws an exception if none found.
D. Retrieves all matching entities.

Answer: A
Explanation: existsBy... methods return a boolean : true if at least one row satisfies the
condition, false otherwise. It effectively checks for the existence of records without retrieving
them.

21. How can you optimize a pagination query to avoid the overhead of a count query?
A. Use Slice<T> or return a List<T> instead of Page<T> .
B. Always include a manual count query in @Query .
C. Use an SQL hint to skip counting.
D. It’s not possible; Page<T> always counts.

Answer: A
Explanation: Unlike Page<T> , returning a Slice<T> or even just a List<T> will not trigger a
count query. Use Slice<T> when you only need to know if more pages exist (the slice has
methods like hasNext() ) 8 .

22. In Spring Data JPA, what annotation is typically used on the entity to define a static named
query?
A. @Query on the repository method.
B. @NamedQuery on the entity 19 .
C. @StaticQuery on the entity.
D. @NamedNativeQuery on the repository.

Answer: B
Explanation: Named queries can be defined with the @NamedQuery annotation on the JPA entity
class. These JPQL queries are then identified by their name (e.g. User.findByEmailAddress ) 19 .

23. Which of the following is true about the @Transactional annotation in Spring Data?
A. It only applies to service layer and not to repositories.
B. It only works on public methods, due to proxy-based AOP limitations.
C. It can be applied to private methods as well.
D. Transactions always start at application startup.

8
Answer: B
Explanation: Spring’s transaction management is proxy-based by default, so @Transactional
only works on public methods. Internal or private method calls won’t go through the proxy and thus
will not be transactional.

24. How would you perform a bulk update or delete in Spring Data JPA?
A. Execute a loop of repository saves.
B. Use a repository method annotated with @Modifying and @Query 20 .
C. Use saveAll() .
D. Bulk updates are not supported by Spring Data JPA.

Answer: B
Explanation: For bulk updates or deletes, use a repository method with @Query specifying the
JPQL (or SQL) and annotate it with @Modifying along with @Transactional . For example:

@Modifying @Transactional
@Query("delete from User u where u.active = false")
void deleteInactiveUsers();

(Without @Transactional , it won’t run in a transaction.) 20 .

25. What does calling saveAll(Iterable<T> entities) on CrudRepository return by


default?
A. A List<T> of saved entities.
B. An Iterable<T> of saved entities.
C. void .
D. A Page<T> .

Answer: B
Explanation: In CrudRepository , the saveAll() method returns an Iterable<T> . However,
JpaRepository (which extends CrudRepository ) overrides saveAll() to return a
List<T> 21 1 .

26. Which of these is not a valid query keyword in Spring Data derived queries?
A. Between
B. Containing
C. All
D. IgnoreCase

Answer: C
Explanation: Between , Containing , and IgnoreCase are valid keywords. There is no All
keyword. (To get all results, you use methods like findAll() without keywords.)

27. How do you paginate and sort results in Spring Data JPA without writing a query?
A. Use EntityManager manually.

9
B. Add a Pageable parameter and/or Sort parameter to the repository method.
C. It cannot be done without @Query .
D. Use @OrderBy annotation on the entity fields.

Answer: B
Explanation: You can simply add a Pageable and/or Sort parameter to your repository method
signature and Spring Data will automatically apply it. For example: List<User>
findByLastname(String lastname, Sort sort) or
Page<User> findByLastname(String lastname, Pageable page) .

28. What is the effect of calling flush() on a Spring Data JPA repository?
A. It clears the persistence context.
B. It synchronizes pending changes to the database immediately.
C. It rolls back the current transaction.
D. It refreshes entities from the database.

Answer: B
Explanation: Calling flush() forces Hibernate (or the JPA provider) to execute the SQL for any
pending changes (insert/update/delete) in the persistence context to the database.

29. Which of the following is true about @Query with nativeQuery=true ?


A. You must use table names as defined in entities, not SQL table names.
B. You can write raw SQL, but may need a countQuery for pagination.
C. Spring Data will convert it to JPQL automatically.
D. It does not support parameter binding.

Answer: B
Explanation: @Query(nativeQuery=true) allows raw SQL. When using pagination with native
queries, you should provide a countQuery explicitly, because Spring Data cannot derive it for you
22 .

30. What happens if you call a repository method from another method in the same class and the
called method is annotated @Transactional with REQUIRES_NEW ?
A. A new transaction will always be started.
B. No new transaction will start because the call does not go through the proxy.
C. It will cause a runtime exception.
D. The called method is ignored.

Answer: B
Explanation: Spring’s transaction annotations work via proxies, so an internal method call does not
go through the proxy. As a result, the REQUIRES_NEW setting on a private or internal call will be
ignored (the outer transaction continues) 23 .

31. How do you implement a custom repository method that uses JPA Criteria (Specification) logic?
A. Implement it in the service layer.
B. Extend JpaSpecificationExecutor and write a Specification<T> .

10
C. Only use JPQL with @Query .
D. Use Spring Data REST.

Answer: B
Explanation: To use criteria (Specification) logic, extend JpaSpecificationExecutor<T> in your
repository and then call methods like findAll(Specification<T>) , passing a
Specification instance. This lets you build queries using the JPA Criteria API in a type-safe way.

Spring Security MCQs


1. In Spring Security 5.7 and later, how is HTTP security typically configured?
A. By extending WebSecurityConfigurerAdapter .
B. By defining a SecurityFilterChain bean 24 .
C. Using XML <http> elements.
D. With system properties.

Answer: B
Explanation: As of Spring Security 5.7, WebSecurityConfigurerAdapter is deprecated. The
recommended approach is to create a @Bean of type SecurityFilterChain and configure
HttpSecurity inside it 24 .

2. Which annotation enables method-level security (e.g. @PreAuthorize ) in Spring Security 6?


A. @EnableWebSecurity
B. @EnableGlobalMethodSecurity
C. @EnableMethodSecurity 25

D. @EnableSecurity

Answer: C
Explanation: In recent versions (5.6+), @EnableMethodSecurity is used to activate method-level
security (replacing the older @EnableGlobalMethodSecurity ). It enables annotations like
@PreAuthorize and @Secured on methods 25 .

3. What authority does the expression hasRole('ADMIN') check for in Spring Security?
A. ADMIN (no prefix)
B. ROLE_ADMIN 26

C. Role_ADMIN
D. PERMISSION_ADMIN

Answer: B
Explanation: The hasRole('X') expression actually checks if the authenticated user has the
authority ROLE_X . For example, hasRole('ADMIN') means the user must have the
ROLE_ADMIN authority 26 .

4. By default, Spring Security’s CSRF protection applies to which HTTP methods?


A. All methods (GET, POST, etc.)

11
B. Only GET and HEAD
C. Unsafe methods (POST, PUT, DELETE, etc.) 27

D. It is disabled by default.

Answer: C
Explanation: CSRF protection is enabled by default for state-changing (unsafe) HTTP methods like
POST, PUT, DELETE (and PATCH). Safe methods like GET, HEAD, OPTIONS do not require a CSRF token
27 .

5. In a new Spring Boot application with Spring Security, what are the default username and
password?
A. admin / admin
B. user and a randomly generated password shown in the console 28

C. There is no default user; you must configure one.


D. user / user (both as “user”).

Answer: B
Explanation: By default Spring Security creates an in-memory user named user with a randomly
generated password. The password is printed in the console on startup (e.g. Using generated
security password: <random> ). This default behavior is documented in Spring Security
5.7+ 28 .

6. How can you use a plain-text password with Spring Security’s DelegatingPasswordEncoder ?
A. Prefix the password with {plain}
B. Prefix the password with {noop} 29

C. Disable the password encoder bean.


D. It is not allowed in Spring Security 5+.

Answer: B
Explanation: The default PasswordEncoder in Spring Security is
DelegatingPasswordEncoder , which requires you to specify the encoding id. For plain text (no
encoding), prefix the password with {noop} (e.g. {noop}password ). This tells it to use
NoOpPasswordEncoder 29 .

7. What is the purpose of Spring Security’s “Remember-Me” functionality?


A. To remember user preferences across sessions.
B. To keep a user logged in via a persistent cookie even after the session ends.
C. To store encrypted passwords in the database.
D. To enforce re-authentication after a timeout.

Answer: B
Explanation: “Remember-Me” allows the application to issue a long-lived cookie so that the user can
remain authenticated across browser restarts. It essentially remembers the user’s login beyond the
normal session lifetime.

12
8. Where does a JWT token typically get sent in an HTTP request for authentication?
A. In a cookie named JWT .
B. As a query parameter token .
C. In the Authorization header as Bearer <token> .
D. In the request body.

Answer: C
Explanation: By convention, JWTs are sent in the Authorization HTTP header using the
Bearer scheme (e.g. Authorization: Bearer <token> ). This is the standard approach for
JWT authentication in HTTP.

9. What does it mean for a Spring Security application to be stateless?


A. It doesn’t require login.
B. It does not create an HTTP session; each request must contain all authentication info (e.g. a
token).
C. It stores state in a database instead of memory.
D. It uses SOAP instead of REST.

Answer: B
Explanation: Stateless security means the server does not keep a session for the user. Each request
must carry its own authentication (usually via a token like JWT), and the server won’t store
authentication state between requests.

10. What is the difference between authentication and authorization in Spring Security?
A. Authentication checks “who you are”; authorization checks “what you can access.”
B. They are the same thing.
C. Authentication is role-based; authorization is user-based.
D. Authorization must happen before authentication.

Answer: A
Explanation: Authentication verifies the identity of a user (e.g. username/password), while
authorization determines what that authenticated user is allowed to do or access (roles/
permissions).

11. Which annotation would you use on a method to restrict access to users with the role USER ?
A. @PreAuthorize("hasRole('USER')")
B. @Secured("ROLE_USER")
C. @RolesAllowed("USER")
D. Any of the above (with proper configuration).

Answer: D
Explanation: All listed annotations can restrict access: @PreAuthorize("hasRole('USER')") ,
@Secured("ROLE_USER") , and @RolesAllowed("USER") (with JSR-250 enabled) all effectively
check for the ROLE_USER authority. Note that for hasRole('USER') , Spring adds the ROLE_
prefix automatically.

13
12. What does CSRF (Cross-Site Request Forgery) protection prevent in a web application?
A. Cross-site scripting attacks.
B. Unauthorized commands sent from a user’s browser on behalf of an authenticated user without
their intent.
C. Password brute-force attacks.
D. Data encryption issues.

Answer: B
Explanation: CSRF protection is meant to ensure that state-changing requests (like form
submissions) are intentional and come from the legitimate user. It prevents malicious websites from
making a user’s browser perform actions on another site where they are authenticated.

13. What must a client typically include in a state-changing form request to pass Spring Security’s
CSRF protection?
A. A header X-CSRF-Token or a hidden form field with the CSRF token value.
B. The session ID as a parameter.
C. Nothing – only headers matter.
D. A special cookie named CSRF .

Answer: A
Explanation: Spring Security’s CSRF protection requires a valid CSRF token on unsafe requests. This
token is often included as a hidden form field (in HTML forms) or an HTTP header ( X-CSRF-Token ).
It must match the token the server expects.

14. How can you disable CSRF protection in a Spring Security configuration?
A. It’s enabled by default and cannot be disabled.
B. Call http.csrf().disable() in your HttpSecurity configuration.
C. Set spring.security.csrf.enabled=false in application.properties .
D. CSRF is only for REST APIs, so not needed to disable.

Answer: B
Explanation: To disable CSRF protection (e.g. for a stateless API), you can call
.csrf().disable() on the HttpSecurity object in your security configuration.

15. What is the default behavior of Spring Security regarding session creation and management?
A. Always create a new session for every request.
B. Never create sessions ( STATELESS by default).
C. Creates a session when needed ( IF_REQUIRED ) and stores the security context in it.
D. Only creates sessions on POST requests.

Answer: C
Explanation: By default, Spring Security uses SessionCreationPolicy.IF_REQUIRED , meaning
it will create an HTTP session when necessary (e.g. after successful login) and store the
SecurityContext in it to keep the user authenticated across requests.

14
16. Which password encoder should you use for storing passwords securely in production?
A. NoOpPasswordEncoder (plain text).
B. BCryptPasswordEncoder or another strong encoder.
C. StandardPasswordEncoder (SHA-256-based).
D. PlaintextPasswordEncoder .

Answer: B
Explanation: For production, use a strong adaptive encoder like BCryptPasswordEncoder .
NoOpPasswordEncoder is only for testing (plain text), and StandardPasswordEncoder
(SHA-256) is considered obsolete. BCrypt or PBKDF2 or SCrypt are recommended.

17. How do you allow unauthenticated access to a specific endpoint (e.g. /public ) in Spring
Security?
A. Do nothing; Spring allows all by default.
B. Use http.authorizeRequests().antMatchers("/public").permitAll() .
C. Define @PermitAll on that controller method (requires method security).
D. Both B and C are valid approaches (B is the common way in HTTP config).

Answer: D
Explanation: You can permit all requests to /public by configuring HttpSecurity with
.authorizeRequests().antMatchers("/public").permitAll() . Alternatively, if using
method-level security, you could use @PermitAll on that controller method (with JSR-250
enabled).

18. In OAuth2 (Authorization Code flow), what is exchanged for an access token?
A. The client ID and secret.
B. The authorization code (and client credentials) 30 .
C. The user’s password.
D. Nothing; the access token is generated without input.

Answer: B
Explanation: In the OAuth2 Authorization Code flow, the client exchanges the received authorization
code (plus its client credentials) for an access token. This ensures the token is issued only after user
consent.

19. What does the HttpSecurity.csrf() configuration do when left with defaults?
A. It disables CSRF protection.
B. It enables CSRF protection for unsafe HTTP methods.
C. It throws an error on startup.
D. It only uses CSRF tokens stored in cookies.

Answer: B
Explanation: By default, http.csrf().csrfTokenRepository(...) is enabled (the default
config), which protects against CSRF for unsafe methods. Calling
.csrf(Customizer.withDefaults()) explicitly just uses the default CSRF behavior (same as
enabling it).

15
20. What is the purpose of the @EnableWebSecurity annotation?
A. It enables web (HTTP) security in the application.
B. It turns on CSRF protection only.
C. It scans for @Controller classes.
D. It initializes an in-memory database.

Answer: A
Explanation: @EnableWebSecurity (on a @Configuration class) triggers the Spring Security
configuration for web applications. It allows customization of WebSecurity / HttpSecurity and
typically is included alongside security beans.

21. How do you configure HTTP Basic authentication with Spring Security?
A. Call http.httpBasic() on HttpSecurity .
B. By default Spring uses HTTP Basic.
C. Include a BasicAuthFilter bean.
D. Use @EnableBasicAuth .

Answer: A
Explanation: To enable HTTP Basic auth, you include .httpBasic() in your HttpSecurity
configuration. For example:

http.authorizeRequests().anyRequest().authenticated()
.and().httpBasic();

22. Which HTTP status code does Spring Security return for unauthorized (not authenticated)
access attempts to protected endpoints?
A. 200 OK
B. 401 Unauthorized
C. 403 Forbidden
D. 302 Found (redirect to login)

Answer: B
Explanation: If a request is unauthenticated, Spring Security responds with HTTP 401
(Unauthorized). If a user is authenticated but not permitted to access the resource, it returns 403
(Forbidden). In stateless or REST setups, 401 is common for missing credentials.

23. How can you provide custom user details (username/password) to Spring Security?
A. Implement UserDetailsService and register it as a bean.
B. Always rely on the default in-memory user.
C. Use @User on a class.
D. Put credentials in application.properties as spring.security.user .

Answer: A
Explanation: To use a custom user store, implement UserDetailsService (or extend

16
JdbcUserDetailsManager , etc.) and register it as a bean. This service loads users by username.
(You can also configure basic user/password in properties or define in-memory users.)

24. What’s the effect of calling .authorizeRequests().antMatchers("/


admin").hasRole("ADMIN") in the security config?
A. It allows all users to access /admin .
B. It restricts /admin to users with ROLE_ADMIN .
C. It restricts /admin to users with the authority "ADMIN" .
D. It has no effect without .anyRequest() .

Answer: B
Explanation: antMatchers("/admin").hasRole("ADMIN") means only users who have the
ROLE_ADMIN authority can access /admin . (Spring automatically adds the ROLE_ prefix for
hasRole("ADMIN") .)

25. Which of the following defines an OAuth2 Resource Server in Spring Security?
A. http.oauth2ResourceServer()
B. @EnableResourceServer (legacy)
C. Both (A) in newer Spring Security (no annotation), and (B) in older OAuth2 libraries.
D. @EnableOAuth2Client .

Answer: C
Explanation: In Spring Security 5+, you typically configure HttpSecurity with
http.oauth2ResourceServer() and related methods. (The older Spring OAuth module used
@EnableResourceServer , but that is now deprecated in favor of the new config.)

26. How do you configure Spring Security to allow frame embedding (for H2 console, etc.)?
A. Spring Security does this by default.
B. Call http.headers().frameOptions().disable() .
C. Add X-Frame-Options: SAMEORIGIN header manually.
D. Use @EnableFrame .

Answer: B
Explanation: By default, Spring Security sets X-Frame-Options: DENY . To allow embedding (e.g.
for H2 console), disable frameOptions with: http.headers().frameOptions().disable() in
the security config.

27. What happens if you omit .csrf().disable() in a REST API secured by Spring Security?
A. Nothing; CSRF only affects web apps.
B. CSRF protection is still active, so state-changing endpoints will be blocked without a token.
C. Spring will throw an exception on startup.
D. CSRF is irrelevant for APIs so it's ignored.

Answer: B
Explanation: Even for APIs, CSRF protection is enabled by default. If you do not disable CSRF, state-
changing requests (POST, etc.) will require a valid CSRF token and otherwise be rejected.

17
28. In Spring Security expressions, what is the difference between hasRole('USER') and
hasAuthority('ROLE_USER') ?
A. There is no difference; both check for authority ROLE_USER .
B. hasRole('USER') checks a session attribute, hasAuthority checks roles.
C. hasRole does not require the ROLE_ prefix, hasAuthority does.
D. hasRole is only for OAuth2.

Answer: C
Explanation: hasRole('X') implicitly adds the ROLE_ prefix (so it checks for authority
ROLE_X ), while hasAuthority('Y') checks the exact authority name you specify. Thus
hasRole('USER') and hasAuthority('ROLE_USER') are equivalent.

29. Which filter processes form-based login in Spring Security’s filter chain?
A. UsernamePasswordAuthenticationFilter
B. FormLoginFilter
C. BasicAuthenticationFilter
D. RememberMeAuthenticationFilter

Answer: A
Explanation: For form login (default Spring Security form),
UsernamePasswordAuthenticationFilter handles the submission of username/password and
attempts authentication.

30. What header is added to prevent clickjacking, and how is it configured by default?
A. X-Frame-Options: DENY , enabled by default.
B. X-Content-Type-Options: nosniff , disabled by default.
C. Content-Security-Policy: frame-ancestors 'none' , enabled by default.
D. Strict-Transport-Security , disabled by default.

Answer: A
Explanation: Spring Security by default adds X-Frame-Options: DENY to responses, which
prevents the app from being framed. This is part of clickjacking protection. (It can be customized or
disabled as needed.)

31. How can you enable CORS (Cross-Origin Resource Sharing) with Spring Security?
A. It's enabled by default.
B. Use http.cors() in the security config and define a CorsConfigurationSource bean.
C. Use @CrossOrigin on controller methods only.
D. Add CORS headers manually in each response.

Answer: B
Explanation: You must enable CORS in Spring Security by calling http.cors() . You also need to
provide a CorsConfigurationSource bean that defines the allowed origins, methods, etc. The
@CrossOrigin annotation or manual headers are alternatives but the recommended way is via
Spring Security config and bean.

18
32. What is the purpose of the AuthenticationManager in Spring Security?
A. It manages the user sessions.
B. It validates credentials and constructs an Authentication object on login.
C. It stores user details in memory.
D. It generates JWT tokens.

Answer: B
Explanation: An AuthenticationManager (often ProviderManager ) is responsible for
authenticating credentials (e.g. username/password) by delegating to
AuthenticationProvider (s). If successful, it returns a fully populated Authentication (user
with roles).

33. In Spring Security’s filter chain, which filter comes first: BasicAuthenticationFilter or
UsernamePasswordAuthenticationFilter ?
A. BasicAuthenticationFilter
B. UsernamePasswordAuthenticationFilter
C. They run in parallel.
D. Order is undefined.

Answer: B
Explanation: The UsernamePasswordAuthenticationFilter (form login) is typically placed
before the BasicAuthenticationFilter (HTTP Basic auth) in the filter chain.

34. What does the @Order annotation do when placed on a WebSecurityConfigurerAdapter


or SecurityFilterChain bean?
A. Determines the order of HTTP handlers.
B. Specifies the filter chain’s precedence.
C. It has no effect.
D. Orders database queries.

Answer: B
Explanation: If you define multiple security configurations (multiple filter chains), you can use
@Order to control which one applies first (Spring will use the first matching chain). Lower numbers
have higher priority.

35. How does Spring Security differentiate between a successful and failed authentication
attempt in an HTTP response?
A. Success always returns 200 OK; failure returns 401 (or redirect to login).
B. Both return 200 OK.
C. Success returns 302 Found; failure returns 500.
D. It only logs; responses are always 200.

Answer: A
Explanation: On successful authentication, the user proceeds (often a 200 or a redirect to original
URL). On failure, Spring Security typically responds with a 401 Unauthorized (or redirects to the login
page in web apps).

19
36. What does the Spring Security expression hasAuthority('permission:read') or
hasRole('ADMIN') check?
A. Authority permission:read or authority ROLE_ADMIN .
B. Group membership.
C. Cookie values.
D. Username equals ADMIN.

Answer: A
Explanation: hasAuthority('permission:read') checks for exactly that authority.
hasRole('ADMIN') checks for ROLE_ADMIN . So the combined expression allows users with
either the permission:read authority or the ROLE_ADMIN authority.

37. What is the function of UserDetailsService in Spring Security?


A. It manages HTTP requests.
B. It retrieves user details (username, password, roles) typically from a database for authentication.
C. It encrypts passwords.
D. It sends emails to users.

Answer: B
Explanation: UserDetailsService is an interface with a method
loadUserByUsername(String username) . Implementations fetch user information (username,
password, granted authorities) from a data source so Spring Security can perform authentication.

38. How do you require HTTPS for all requests in Spring Security?
A. http.requiresChannel().anyRequest().requiresSecure()
B. Set server.ssl.enabled=true .
C. Use http.secure().all() .
D. Spring Security cannot enforce HTTPS.

Answer: A
Explanation: In the security config, use
http.requiresChannel().anyRequest().requiresSecure() to require an HTTPS channel for
all requests. This will redirect HTTP requests to HTTPS by default.

39. Which of the following is a valid way to configure password encoding in Spring Security 5?
A. <bean id="passwordEncoder"
class="org.springframework.security.crypto.password.NoOpPasswordEncoder"/>
B. PasswordEncoder encoder = new BCryptPasswordEncoder(); and use it for
UserDetailsService .
C. Prefix stored password strings with an encoding id (like {bcrypt} or {noop} ).
D. All of the above (depending on context).

Answer: D
Explanation: All methods are valid: you can define a PasswordEncoder bean (like BCrypt). The
DelegatingPasswordEncoder approach allows prefixing stored passwords with {bcrypt} ,

20
{noop} , etc., to pick the encoding on the fly. Note: option A is actually a class; in modern Spring,
you’d use PasswordEncoderFactories or builders.

40. How can you test secured methods in Spring without disabling security?
A. It’s not possible; you must disable security for tests.
B. Use @WithMockUser or @WithUserDetails in Spring Security test support.
C. Use @SpringBootTest only.
D. Use a special test profile.

Answer: B
Explanation: Spring Security’s test module provides annotations like @WithMockUser and
@WithUserDetails to simulate an authenticated user with given roles/authorities for testing
method-security or web-security endpoints without modifying the actual security configuration.

Sources: Official Spring Data and Spring Security documentation and references 1 13 3 6 15 5 12

2 9 27 26 28 29 .

1 21java - What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA? -
Stack Overflow
https://stackoverflow.com/questions/14014086/what-is-difference-between-crudrepository-and-jparepository-interfaces-in-spring

2 PagingAndSortingRepository (Spring Data Core 3.5.1 API)


https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/
PagingAndSortingRepository.html

3 java - Technical differences between Spring Data JPA's findFirst and findTop - Stack Overflow
https://stackoverflow.com/questions/38045439/technical-differences-between-spring-data-jpas-findfirst-and-findtop

4 5 10 17 19 JPA Query Methods :: Spring Data JPA


https://docs.spring.io/spring-data/jpa/reference/jpa/query-methods.html

6 7 11 20 23 Transactionality :: Spring Data JPA


https://docs.spring.io/spring-data/jpa/reference/jpa/transactions.html

8 22 java - spring data jpa @query and pageable - Stack Overflow


https://stackoverflow.com/questions/22345081/spring-data-jpa-query-and-pageable

9 java - Page<> vs Slice<> when to use which? - Stack Overflow


https://stackoverflow.com/questions/49918979/page-vs-slice-when-to-use-which

12 Custom Repository Implementations :: Spring Data JPA


https://docs.spring.io/spring-data/jpa/reference/repositories/custom-implementations.html

13 16 Advanced Spring Data JPA - Specifications and Querydsl


https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

14 15 Query by Example :: Spring Data JPA


https://docs.spring.io/spring-data/jpa/reference/repositories/query-by-example.html

21
18 Supported Keywords in Query Method
https://docs.oracle.com/en/database/other-databases/nosql-database/21.1/java-driver-table/supported-keywords-query-
methods.html

24 Spring Security without the WebSecurityConfigurerAdapter


https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter/

25 EnableMethodSecurity (spring-security-docs 6.5.1 API)


https://docs.spring.io/spring-security/reference/api/java/org/springframework/security/config/annotation/method/
configuration/EnableMethodSecurity.html

26 Method Security :: Spring Security


https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html

27 30 Cross Site Request Forgery (CSRF) :: Spring Security


https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html

28 java - What is username and password when starting Spring Boot with Tomcat? - Stack Overflow
https://stackoverflow.com/questions/37285016/what-is-username-and-password-when-starting-spring-boot-with-tomcat

29 Password Storage :: Spring Security


https://docs.spring.io/spring-security/reference/features/authentication/password-storage.html

22

You might also like