← TestGorilla Interview Insights
Explain that you create a single ApplicationContext (e.g., ClassPathXmlApplicationContext or AnnotationConfigApplicationContext) and pass multiple configuration locations to its constructor. Then emphasize how to share it across the application, such as exposing it via a static holder or using Spring's ContextLoaderListener in a web app.
Pro tip: Mention that in modern Spring Boot, this is largely handled automatically, but understanding the underlying mechanism shows depth. Also, warn against creating multiple contexts, which can lead to duplicate beans and memory issues.
Decide between XML-based (ClassPathXmlApplicationContext) or annotation-based (AnnotationConfigApplicationContext) depending on your configuration style.
Pass an array of config locations to the container constructor, e.g., new ClassPathXmlApplicationContext("services.xml", "daos.xml").
Use a static singleton holder or integrate with a web framework via ContextLoaderListener to make the context globally accessible.
Guard against multiple context creations by centralizing initialization in a bootstrap class or using Spring's built-in support.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.
Went with @Before since you want the arguments before the method runs, not after.
Evaluate each advice type based on when it executes relative to the method and what information it can access. For logging method arguments, you need access to the arguments before the method executes, so @Before is the most direct choice. However, consider if you also need to log the outcome or handle exceptions, which might require @Around.
Pro tip: Mention that @Around provides the most flexibility but comes with complexity and potential performance overhead; for simple argument logging, @Before is sufficient and cleaner. Also, note that @AfterReturning cannot access arguments unless you use a binding technique, and @After executes after the method, so arguments might be modified.
Identify that the goal is to log method arguments for auditing, which requires capturing the arguments at method invocation time.
Consider when each advice executes and what it can access: @Before runs before method execution and can access arguments; @After runs after and can access arguments but they might be modified; @AfterReturning runs after successful return and can access return value but not arguments directly; @Around wraps the method and can access arguments and control execution.
Since auditing requires logging arguments as they are passed, @Before is the simplest and most appropriate because it executes before the method and has access to the original arguments.
Acknowledge that @Around could also work and provides more control (e.g., logging both arguments and return value), but it introduces complexity and potential performance overhead. For pure argument logging, @Before is sufficient.
Select @Before as the answer, explaining that it directly fulfills the requirement without unnecessary complexity.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.
Start by acknowledging the problem: when multiple beans implement the same interface, Spring's autowiring by type fails with NoUniqueBeanDefinitionException. Then explain the main solutions—@Primary, @Qualifier, and custom qualifiers—and discuss when to use each, emphasizing trade-offs like coupling and maintainability.
Pro tip: Mention that constructor injection with @Qualifier is preferred over field injection because it makes dependencies explicit and testable, and that @Primary is best for a default implementation while @Qualifier is for specific cases.
Explain that when multiple beans of the same type exist, Spring cannot resolve by type alone and throws NoUniqueBeanDefinitionException.
Mark one bean as @Primary to indicate it should be chosen by default when no other qualifier is specified.
Apply @Qualifier with the bean name at the injection point to select a specific bean, which can be combined with @Primary.
Create custom annotations meta-annotated with @Qualifier for more semantic and type-safe selection, reducing string-based errors.
Compare approaches: @Primary is simple but can hide dependencies; @Qualifier is explicit but couples to bean names; custom qualifiers are clean but add complexity. Recommend constructor injection for testability.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.
Just @Autowired on a field or constructor.
Start by directly answering that field injection via @Autowired is the simplest, then briefly explain why constructor injection is generally preferred for production code. Show awareness of trade-offs between simplicity and maintainability, and mention that Spring also supports setter injection and @Resource.
Pro tip: Acknowledge that while field injection is simplest to write, it hides dependencies and makes testing harder; demonstrating this nuance shows you think beyond just 'making it work'.
State that the simplest way is field injection using @Autowired on a private field, as it requires no constructor or setter.
Briefly describe that Spring uses reflection to inject the dependency after bean instantiation, and that no explicit configuration is needed if component scanning is enabled.
Mention that field injection is discouraged for production because it prevents immutability, complicates unit testing, and hides dependencies. Constructor injection is preferred for mandatory dependencies.
Note that setter injection is another option for optional dependencies, and @Resource or @Inject can be used for standardization.
Summarize that while field injection is simplest, constructor injection is the recommended approach for maintainable, testable code.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.
Start by clarifying that the easiest way is to use Spring's BeanPropertyRowMapper, which automatically maps columns to bean properties by name. Then explain how to use it with JdbcTemplate.query, and briefly mention alternatives like custom RowMapper for more control. Highlight that this approach reduces boilerplate and is ideal for simple mappings.
Pro tip: Mention that BeanPropertyRowMapper requires the target class to have a default constructor and setters, and that column names must match property names (or use aliases in SQL). Also note that for performance-critical or complex mappings, a custom RowMapper might be better.
Explain that JDBC ResultSet is low-level and manually mapping each column to object fields is tedious and error-prone.
State that Spring provides BeanPropertyRowMapper, which automatically maps rows to Java beans by matching column names to property names.
Demonstrate how to pass a new instance of BeanPropertyRowMapper to JdbcTemplate.query, e.g., jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MyObject.class)).
Mention that for complex mappings or performance, a custom RowMapper implementation might be preferable, and that BeanPropertyRowMapper uses reflection which can be slower.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.
Identify DataSource as the correct answer, then briefly explain its role as the standard JDBC abstraction for connection management in Spring. Mention that the other options are either non-standard or specific implementations, and highlight how DataSource integrates with Spring's dependency injection and transaction management.
Pro tip: Emphasize that DataSource is an interface, allowing you to swap implementations (e.g., HikariCP, Tomcat JDBC) without changing your code, which is crucial for production flexibility. Also, note that Spring Boot auto-configures a DataSource based on the classpath and properties, simplifying setup.
State that DataSource is the standard interface for encapsulating database connections in Spring. Explain that it provides a way to obtain connections without exposing connection details.
Clarify that SQLConnector, MySqlConnector, and MySQLJDBC are not standard Spring bean types; they are either made-up or specific to other frameworks. This shows you understand the Spring ecosystem.
Discuss how DataSource is used by JdbcTemplate, Hibernate, and JPA for database access. Mention that it supports connection pooling and transaction management.
Mention that DataSource can be configured via Java config or XML, and that Spring Boot auto-configures it. Recommend using a connection pool like HikariCP for production.
Explain that choosing DataSource promotes loose coupling and testability, as you can easily mock or swap implementations. This aligns with the 'Technical Trade-offs' category.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.
You can inject a Principal or use SecurityContextHolder to grab the Authentication object.
Explain that Spring Security stores the authenticated principal in the SecurityContext, which can be accessed via SecurityContextHolder or injected as a method argument using @AuthenticationPrincipal. Then describe how to extract the user's details (e.g., username, ID) and log them, emphasizing thread-safety and avoiding sensitive data.
Pro tip: Mention that SecurityContextHolder uses a ThreadLocal by default, so it's safe in synchronous request handling but requires care with async or reactive flows. Also, prefer injecting @AuthenticationPrincipal over static access for testability.
Clarify that Spring Security is typically used, which populates the SecurityContext upon successful authentication.
Use SecurityContextHolder.getContext().getAuthentication() to retrieve the Authentication object, which contains the principal.
Cast the principal to UserDetails or your custom user class to get username, authorities, etc. Alternatively, use @AuthenticationPrincipal to inject the user directly into the controller method.
Use a logger to record relevant user information (e.g., username) at an appropriate level, ensuring no sensitive data like passwords are logged.
Note that SecurityContextHolder is thread-bound; for async requests, propagate the context or use other mechanisms. Prefer dependency injection for testability.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.
Start by explaining that @PreAuthorize('hasRole('ROLE_ABC')') often fails due to the automatic 'ROLE_' prefix handling in Spring Security, which can lead to double-prefixing. Then, describe the correct usage: either use hasRole('ABC') or hasAuthority('ROLE_ABC') depending on your configuration, and verify the user's granted authorities.
Pro tip: Mention that you can enable debug logging for Spring Security to see the exact authorities being checked, which quickly reveals prefix mismatches. This shows you know how to troubleshoot efficiently.
Explain that hasRole automatically adds the 'ROLE_' prefix, so using 'ROLE_ABC' results in checking for 'ROLE_ROLE_ABC', causing access denied.
State that hasRole should be used with the role name without the prefix (e.g., hasRole('ABC')), while hasAuthority expects the full authority string (e.g., hasAuthority('ROLE_ABC')).
Describe how to verify the actual authorities assigned to the user, ensuring they match the expected format (with or without 'ROLE_' prefix).
Mention that custom RolePrefix or custom PermissionEvaluator can alter behavior, so review security configuration if the issue persists.
Suggest enabling debug logging for Spring Security to see the exact access decision process and identify mismatches.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.