Spring Core, Aspect-Oriented Programming, Data Access, and Security Assessment
System DesignModel answerLast updated
Evaluate key Spring concepts including ApplicationContext configuration, AOP advice selection, dependency injection, JdbcTemplate mapping, DataSource configuration, and Security authorization rules.
Answer the following questions covering Spring Framework fundamentals:
- How do you construct a single, application-wide Spring IoC container that aggregates multiple configuration sources?
- Which AOP advice type (
@Before,@After,@Around, or@AfterReturning) is best suited for logging incoming method parameters for audit purposes? Explain why. - How do you handle dependency injection when multiple bean definitions implement the same target interface?
- What is the idiomatic standard for injecting dependencies into a component in modern Spring applications?
- What is the simplest built-in class provided by Spring JDBC to map a database
ResultSetrow directly to a POJO/Java Bean? - Which standard object type should be registered as a Spring bean to manage database connections for MySQL or PostgreSQL? Choose one:
DataSource,SQLConnector,MySqlConnector, orMySQLJDBC. - How can you retrieve the details of the logged-in user inside a Spring Web MVC controller method?
- Why might
@PreAuthorize("hasRole('ROLE_ADMIN')")throw an access denied exception even if the user has administrative privileges, and how should it be written correctly?
Hints
Hint 1
For question 2, choose the advice type that runs prior to method execution and does not risk failing to execute if an exception occurs.
Hint 2
For question 5, think about the utility class that converts column names using snake_case to Java bean properties using camelCase.
Hint 3
For question 8, check whether the method implicitly prepends a specific prefix to authority names.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Summary Table
| # | Topic | Solution / Best Practice |
|---|---|---|
| 1 | Container Initialization | Instantiate a single ApplicationContext (e.g., AnnotationConfigApplicationContext) passing all configuration classes, or use @Import. |
| 2 | AOP Advice | @Before advice. |
| 3 | Disambiguation | Use @Qualifier("beanName") at the injection point or annotate the default bean with @Primary. |
| 4 | Dependency Injection | Constructor injection (with implicit @Autowired). |
| 5 | JDBC Row Mapping | BeanPropertyRowMapper (or DataClassRowMapper for modern Java records). |
| 6 | DB Abstraction | DataSource (typically backed by a connection pool like HikariCP). |
| 7 | Principal Access | Controller parameter injection (@AuthenticationPrincipal, Authentication, or Principal) or querying SecurityContextHolder. |
| 8 | Role Authorization | Use hasRole('ADMIN') (Spring automatically prepends ROLE_), or use hasAuthority('ROLE_ADMIN'). |
Detailed Walkthrough
1. Unified IoC Container Configuration
To aggregate multiple configuration classes into a single shared IoC container:
// Java-based Configuration
ApplicationContext context = new AnnotationConfigApplicationContext(
DatabaseConfig.class,
ServiceConfig.class,
SecurityConfig.class
);
Key Mechanics:
- Passing multiple classes to the constructor merges all bean definitions into a unified registry, allowing cross-file dependency resolution.
- Alternatively, a primary configuration class can aggregate child configurations using the
@Import({DatabaseConfig.class, ServiceConfig.class})annotation. - In web environments using classic Spring,
ContextLoaderListenerreads a delimited list fromcontextConfigLocation. Spring Boot handles context creation automatically duringSpringApplication.run().
2. Selecting AOP Advice for Audit Logging
Correct Answer: @Before
@Aspect
@Component
public class AuditLoggingAspect {
@Before("execution(* com.example.service..*(..))")
public void logInputArguments(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
String methodName = joinPoint.getSignature().toShortString();
log.info("Executing {} with arguments: {}", methodName, Arrays.toString(args));
}
}
Trade-off Analysis:
@Before: Ideal because method arguments are captured right before execution starts. It executes regardless of whether the business method eventually succeeds or throws an exception, and it cannot disrupt execution flow by failing to callproceed().@Around: Can achieve the same result, but introduces unnecessary complexity. If the advice omitsjoinPoint.proceed(), execution halts.@AfterReturning: Fails to log requests if the target method throws an exception prior to completion.@After(Finally): Runs post-execution, which is non-idiomatic for pre-execution parameter capture.
3. Resolving Ambiguous Dependencies
When multiple beans satisfy a single interface, Spring throws a NoUniqueBeanDefinitionException.
Resolution Options:
-
@Qualifier: Explicitly selects a target bean by identifier at the injection site.@Service public class PaymentProcessor { private final PaymentGateway gateway; public PaymentProcessor(@Qualifier("stripeGateway") PaymentGateway gateway) { this.gateway = gateway; } } -
@Primary: Marks one implementation as the default fallback when no qualifier is specified. -
Collection Injection: Inject a
List<PaymentGateway>orMap<String, PaymentGateway>to access all registered implementations.
4. Idiomatic Dependency Injection
The recommended standard across modern Spring applications is Constructor Injection.
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final NotificationService notificationService;
// @Autowired is implicit on single constructors as of Spring 4.3
public OrderService(OrderRepository orderRepository, NotificationService notificationService) {
this.orderRepository = orderRepository;
this.notificationService = notificationService;
}
}
Benefits over Field Injection (@Autowired private Repo repo):
- Allows fields to be declared
final, guaranteeing immutability. - Prevents partial object construction and
NullPointerExceptionrisks. - Simplifies unit testing by enabling direct instantiation without Spring test runners or reflection.
5. ResultSet Row Mapping
Correct Answer: BeanPropertyRowMapper
List<UserDto> users = jdbcTemplate.query(
"SELECT id, first_name, email_address FROM users",
BeanPropertyRowMapper.newInstance(UserDto.class)
);
How It Works:
- Automatically maps relational columns to target POJO fields, converting database naming (
snake_case) to Java property conventions (camelCase). - Requires the target POJO to have a public default constructor and standard setter methods.
- Note: For modern Java
recordtypes or immutable classes, useDataClassRowMapperinstead.
6. Database Connection Encapsulation
Correct Answer: DataSource (javax.sql.DataSource)
DataSource is the standard Java Database Connectivity (JDBC) interface supported by Spring frameworks, JdbcTemplate, and ORM layers (Hibernate/JPA).
Options like SQLConnector or MySQLJDBC are fictitious names within the Spring API context.
@Bean
public DataSource dataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl("jdbc:mysql://localhost:3306/app_db");
ds.setUsername("db_user");
ds.setPassword("secure_password");
return ds;
}
In production, application contexts should configure a pooled DataSource (such as HikariCP) rather than unpooled wrappers like DriverManagerDataSource.
7. Accessing Authentication Context in Spring MVC
Preferred Approach: Parameter Injection in Controller Methods
@RestController
@RequestMapping("/api/profile")
public class UserProfileController {
@GetMapping
public ResponseEntity<UserProfile> getProfile(@AuthenticationPrincipal CustomUserDetails user) {
log.info("Fetching profile for user ID: {}", user.getId());
return ResponseEntity.ok(user.toProfile());
}
}
Alternative Options:
-
Method arguments of type
java.security.Principalororg.springframework.security.core.Authentication. -
Accessing the static thread-local context anywhere in the execution thread:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
8. Spring Security Role Evaluation Rules
Root Cause:
Spring Security's hasRole('X') expression automatically prepends the string prefix ROLE_ to the evaluated string. Passing "ROLE_ADMIN" results in Spring searching for an authority named ROLE_ROLE_ADMIN, leading to an authorization failure (403 Forbidden).
Correct Usage Patterns:
// Option A: Strip the prefix when using hasRole
@PreAuthorize("hasRole('ADMIN')")
// Option B: Use hasAuthority for exact string matching
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
Key Takeaway:
Use hasRole when adhering to standard role naming conventions (where roles implicitly carry the ROLE_ prefix inside the GrantedAuthority collection). Use hasAuthority when matching exact authority strings (e.g., granular permissions such as READ_PRIVILEGE).