SSM
SSM
1. Are singleton beans in the Spring framework thread-safe?
Answer:
No, they are not thread-safe. When multiple users request a service simultaneously, the container allocates a thread for each request, and these threads concurrently execute business logic. If the logic modifies the singleton's state (e.g., updating a singleton's member property), thread synchronization must be handled explicitly.
Spring itself does not provide thread-safety mechanisms for singleton beans. Developers need to address thread safety and concurrency issues themselves. Typically, beans used in projects (like Service
and DAO
classes) are stateless, which makes singleton beans relatively thread-safe. For stateful beans (e.g., ViewModel
objects), developers must ensure thread safety explicitly.
One simple solution is to change the bean's scope from singleton
to prototype
.
2. What is AOP?
Answer:
AOP (Aspect-Oriented Programming) is used in Spring to extract common behaviors and logic that are not directly related to business concerns but affect multiple objects. This promotes reuse of common modules and reduces coupling. Common use cases include logging and transaction management.
3. Have you used AOP in your project?
Answer:
Yes, we used AOP to record system operation logs in a backend management system. The approach involved using AOP's @Around
advice and pointcut expressions to identify the methods where logs were needed. In the @Around
advice, we extracted parameters such as class and method information, annotations, and request types. These parameters were then saved to the database as operation logs.
4. How are transactions implemented in Spring?
Answer:
Spring transactions are implemented using AOP. It intercepts methods annotated with @Transactional
, starting a transaction before the method execution and committing or rolling back the transaction based on the outcome of the method.
5. What scenarios can cause transaction failure in Spring?
Answer:
Here are a few scenarios that can cause transaction failures:
- If an exception is caught and handled internally without being re-thrown, the transaction will not roll back.
- If a checked exception is thrown but
rollbackFor
is not explicitly set toException
in the@Transactional
annotation, the transaction may not roll back. - If the method annotated with
@Transactional
is notpublic
, the transaction may not work as expected.
6. What is the lifecycle of a Spring bean?
Answer:
The lifecycle of a Spring bean includes:
- Retrieving bean definitions from
BeanDefinition
. - Instantiating the bean using its constructor.
- Performing dependency injection via setter methods or
@Autowired
. - Handling beans that implement the
Aware
interface. - Executing
BeanPostProcessor
's pre-processing. - Initializing the bean (via
InitializingBean
or custominit-method
). - Executing
BeanPostProcessor
's post-processing (proxy creation may occur here). - Destroying the bean during container shutdown.
7. What is circular dependency in Spring?
Answer:
Circular dependency occurs when two or more beans depend on each other, forming a closed loop. Spring resolves most circular dependencies using a three-level cache:
- Level 1 Cache: The singleton pool, storing fully initialized beans.
- Level 2 Cache: A cache for early references of beans (partially initialized).
- Level 3 Cache: A cache for
ObjectFactory
instances to create bean proxies.
8. How does Spring resolve circular dependencies?
Answer:
The resolution process is as follows:
- Instantiate Bean A and store its
ObjectFactory
in the level 3 cache. - During Bean A's initialization, it requires Bean B, triggering Bean B's creation process.
- Instantiate Bean B and store its
ObjectFactory
in the level 3 cache. - Bean B requires Bean A, so it retrieves Bean A from the level 3 cache, initializes it partially, and moves it to the level 2 cache.
- Bean B is completed and stored in the level 1 cache.
- Bean A finishes its initialization by injecting Bean B and is then moved to the level 1 cache.
9. How to resolve circular dependencies caused by constructors?
Answer:
Circular dependencies involving constructors cannot be resolved by Spring because the constructor phase is the first step in bean creation. To resolve this, you can use the @Lazy
annotation to delay the creation of one of the beans until it is needed.
10. What is the Spring MVC execution flow?
Answer:
The Spring MVC execution flow is as follows:
- The user sends a request to the front controller (
DispatcherServlet
). - The
DispatcherServlet
consultsHandlerMapping
to find the appropriate handler. HandlerMapping
returns the handler and any interceptors to theDispatcherServlet
.- The
DispatcherServlet
callsHandlerAdapter
. HandlerAdapter
invokes the specific controller method.- The controller executes and returns a
ModelAndView
object. - The
HandlerAdapter
passes theModelAndView
back to theDispatcherServlet
. - The
DispatcherServlet
resolves the view usingViewResolver
. - The resolved view is rendered by the
DispatcherServlet
. - The response is sent back to the user.
11. What is the principle of Spring Boot's auto-configuration?
Answer:
Spring Boot's auto-configuration is based on the @SpringBootApplication
annotation, which combines:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
The core annotation, @EnableAutoConfiguration
, uses @Import
to load configuration classes. These classes are defined in META-INF/spring.factories
and are conditionally loaded based on the environment.
12. What are common annotations in Spring?
Answer:
Common Spring annotations include:
- Bean Declaration Annotations:
@Component
,@Service
,@Repository
,@Controller
.
- Dependency Injection Annotations:
@Autowired
,@Qualifier
,@Resource
.
- Scope Configuration Annotation:
@Scope
.
- Configuration Annotations:
@Configuration
,@ComponentScan
,@Bean
.
- AOP Annotations:
@Aspect
,@Before
,@After
,@Around
,@Pointcut
.
13. What are common annotations in Spring MVC?
Answer:
Common Spring MVC annotations include:
@RequestMapping
: Maps request paths.@RequestBody
: Parses JSON data from HTTP requests.@RequestParam
: Maps HTTP request parameters.@PathVariable
: Extracts path variables from the URL.@ResponseBody
: Converts the return value of a controller method to JSON.@RequestHeader
: Extracts HTTP request header data.- HTTP method-specific mappings such as
@GetMapping
,@PostMapping
, etc.
14. What are common annotations in Spring Boot?
Answer:
Common Spring Boot annotations include:
@SpringBootApplication
: Combines@SpringBootConfiguration
,@EnableAutoConfiguration
, and@ComponentScan
.- REST and web-related annotations:
@RestController
,@GetMapping
,@PostMapping
, etc., which simplify Spring MVC configurations.
15. What is the MyBatis execution flow?
Answer:
The MyBatis execution flow is as follows:
- Read the MyBatis configuration file (
mybatis-config.xml
). - Construct the
SqlSessionFactory
. - Use the
SqlSessionFactory
to create anSqlSession
object. - Use the
SqlSession
to interact with the database. - The
Executor
executes the logic defined in the Mapper'sMappedStatement
. - Perform input parameter mapping.
- Map the results to output objects.
16. Does MyBatis support lazy loading?
Answer:
Yes, MyBatis supports lazy loading. This means data is fetched only when it is needed. Lazy loading can be enabled or disabled by setting the lazyLoadingEnabled
configuration property.
17. What is the underlying principle of lazy loading in MyBatis?
Answer:
The underlying principle of lazy loading is based on CGLIB dynamic proxies:
- MyBatis creates a proxy object using CGLIB.
- When a method on the proxy is called, it checks if the required data is loaded.
- If the data is not loaded, MyBatis executes the appropriate SQL query.
- The results are loaded into the proxy object, and the method call proceeds.
18. Have you used MyBatis' first- and second-level caches?
Answer:
Yes:
- First-Level Cache:
This is a session-scoped cache that stores query results in memory using aPerpetualCache
backed by aHashMap
. It is enabled by default. - Second-Level Cache:
This is a namespace-scoped cache that must be explicitly enabled. It is also based onPerpetualCache
and usesHashMap
for storage.
19. When does MyBatis' second-level cache clear its data?
Answer:
The second-level cache clears data in the following situations:
- When any
insert
,update
, ordelete
operation is performed within the same namespace. - The namespace's cache is invalidated, and all related cached
select
queries are removed.