Spring Container, AOP, JDBC, and Security Fundamentals
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Prompt
Address each of the eight Spring ecosystem scenarios below (selecting the single best option where choices are listed):
- Unified container bootstrap: How do you initialize one
ApplicationContext(IoC container) from several separate configuration sources and share that single instance across the whole application? - Audit-logging advice selection: You want an AOP aspect to record incoming call parameters for audit trails. Select one annotation —
@Before,@After,@Around, or@AfterReturning— and justify your choice. - Disambiguating candidate beans: Several Spring-managed beans implement the same Java interface. How do you instruct Spring which concrete bean to wire into a consumer?
- Minimal dependency wiring: What is the most direct mechanism in Spring for supplying a collaborator bean or external resource to a managed class?
- Automatic row-to-object conversion: When querying relational data through
JdbcTemplate, what built-in helper most concisely turnsResultSetrows into standard JavaBean instances? - MySQL connection abstraction: Which standard bean interface represents and manages connectivity to a MySQL database in Spring? Select one:
DataSource,SQLConnector,MySqlConnector, orMySQLJDBC. - Authenticated caller lookup: Inside a Spring MVC or REST controller endpoint, how can your handler obtain the active caller's identity so you can include it in application logs?
- Role-prefix authorization pitfall: When securing a service method with
@PreAuthorize("hasRole('ROLE_ABC')"), why can legitimate callers still receive an authorization failure, and how should the expression be written instead?
Scope & Expectations
- Give the exact Spring API, annotation, or selected option for each of the eight prompts along with concise, idiomatic Java snippets where helpful.
- Explain why alternative choices or naive approaches fall short (such as container proliferation, proxy self-invocation limits, pooled vs. per-query database connections, and authority prefix conventions).
- Call out practical production safeguards including null checks on anonymous endpoints, boxed types for nullable SQL columns, and enabling AOP and method-level security configuration.
Step-by-step walkthrough
Quick reference: all 8 answers at a glance
Before diving into the details, here is how all eight parts fit into a single Spring web application when an HTTP request arrives:
HTTP Request | v [Spring Security Filter] ---> stores current user in SecurityContext (Q7) | v [Controller Handler] -------> @AuthenticationPrincipal reads user for logging (Q7) | v (calls service through a Spring proxy inside one shared IoC container: Q1, Q3, Q4) [Spring Proxy] -------------> 1. @PreAuthorize("hasRole('ABC')") checks ROLE_ABC (Q8) | 2. @Before advice logs method arguments for auditing (Q2) v [Service -> JdbcTemplate] --> borrows connection from DataSource pool (Q6) maps SQL rows to Java objects via BeanPropertyRowMapper (Q5)And here is the concise answer key for all eight questions:
Q# Topic Direct Answer -- ------------------------------- ----------------------------------------------------------------- 1. One shared IoC container Pass all files to one ClassPathXmlApplicationContext("a.xml", "b.xml") (or AnnotationConfigApplicationContext(A.class, B.class)) once at startup. 2. AOP advice to audit arguments @Before 3. Pick one of several beans @Qualifier("beanName") at the injection point (or @Primary as default). 4. Simplest dependency injection @Autowired (optional on a class with a single constructor since Spring 4.3). 5. Map ResultSet to Java bean BeanPropertyRowMapper (new BeanPropertyRowMapper<>(Customer.class)). 6. MySQL connection bean type DataSource (javax.sql.DataSource, backed by a pool like HikariDataSource). 7. Current user in MVC/REST @AuthenticationPrincipal UserDetails user (or Principal / Authentication method parameter, or SecurityContextHolder.getContext().getAuthentication()). 8. hasRole('ROLE_ABC') denied hasRole('X') checks authority "ROLE_X"; write @PreAuthorize("hasRole('ABC')") for role ROLE_ABC, or hasAuthority('ABC') if stored without "ROLE_".Shared IoC container from multiple config files (Q1)
Inversion of Control (IoC) means letting the framework construct and connect your application objects instead of calling
newmanually inside every class. A bean is simply a Java object whose lifecycle (creation, wiring, and cleanup) is managed by Spring's IoC container, represented by theApplicationContextinterface.To load multiple configuration files into one single container, pass all file paths (or configuration classes) to a single
ApplicationContextconstructor so every bean lives in the same registry and can reference beans from the other files:// XML configuration: pass multiple classpath locations to one constructor ConfigurableApplicationContext xmlContext = new ClassPathXmlApplicationContext("services.xml", "repositories.xml", "security.xml"); xmlContext.registerShutdownHook(); // closes pools cleanly when the JVM exits // Java configuration: pass multiple @Configuration classes to one constructor ConfigurableApplicationContext javaContext = new AnnotationConfigApplicationContext(ServiceConfig.class, DataConfig.class); javaContext.registerShutdownHook();Alternatively, one root configuration can pull in the others using
<import resource="repositories.xml"/>in XML,@Import(DataConfig.class)in Java config, or@ImportResource("classpath:legacy.xml")to combine both styles.To keep that single container active across the whole JVM process, instantiate it once at startup and let Spring wire dependencies everywhere rather than calling
new ClassPathXmlApplicationContext(...)inside methods:- Spring Boot:
SpringApplication.run(App.class, args)builds and shares one rootApplicationContextautomatically. - Classic Servlet web app:
ContextLoaderListenerreadscontextConfigLocation(listing multiple XML files) once when the web server starts and stores the single root context in theServletContext. - Standalone app: create the context once in
main(...)and keep that single reference.
Why creating it once is critical: Spring's default singleton scope means one bean instance per container, not per JVM. If a developer accidentally calls
new ClassPathXmlApplicationContext(...)inside an HTTP handler, every request builds a brand-new container and brand-new singletons. For example, ifrepositories.xmlconfigures a database connection pool of10connections, just16such calls allocate16 * 10 = 160connections — already exceeding MySQL's defaultmax_connections = 151limit and crashing subsequent requests.- Spring Boot:
Auditing method arguments with @Before advice (Q2)
Aspect-Oriented Programming (AOP) is a way to attach cross-cutting behavior (such as audit logging, metrics, or transactions) around methods without copying boilerplate code into every business class. An advice is the action taken by an aspect at a particular moment, and a join point (
JoinPoint) is the specific method call being intercepted, carrying the method name and its runtime arguments.Correct choice:
@Before.Why
@Beforebeats the other three options when auditing method arguments:Advice When it runs Why it fits (or fails) for argument auditing ---------------- ----------------------------------- ---------------------------------------------------- @Before Right before the target method BEST: runs on every call (even if the method later throws), sees original unmodified arguments, and cannot accidentally swallow the return value. @AfterReturning Only after a normal return FAILS: skips calls that throw an exception, hiding failed or unauthorized attempts from the audit log. @After In a finally block after the method RISKY: if the method mutates an input object in place (e.g., dto.setAmount(0)), you log the altered value; if a call hangs forever, nothing is logged. @Around Wraps before and after the call OVERKILL: requires calling pjp.proceed() and returning its result; forgetting either silently skips the method or returns null.Spring's official AOP guide gives a simple rule: always pick the least powerful advice that solves the job. Because we only need to log the incoming arguments,
@Beforeis clean and safe:@Aspect @Component public class AuditAspect { private static final Logger log = LoggerFactory.getLogger(AuditAspect.class); @Before("execution(* com.example.service.*.*(..))") public void auditArguments(JoinPoint joinPoint) { log.info("Audit call={} args={}", joinPoint.getSignature().toShortString(), Arrays.toString(joinPoint.getArgs())); } }One important operational detail: Spring AOP works by wrapping each bean in a proxy (an auto-generated wrapper object that intercepts incoming method calls before forwarding them to your real class). You enable it with
@EnableAspectJAutoProxy(automatic in Spring Boot's AOP starter). Because interception happens at the proxy boundary, callingthis.helperMethod(...)inside the same class bypasses the proxy and does not trigger@Before.Injecting dependencies with @Autowired and @Qualifier (Q3–Q4)
Dependency injection (DI) means a class declares what collaborators it needs, and the IoC container supplies them automatically instead of the class looking them up or constructing them itself.
Item 4 — Minimal dependency wiring:
@Autowired. When a class is registered as a Spring bean (@Component,@Service,@Repository, or@Controller),@Autowiredtells Spring to find a matching bean by type and pass it in. Since Spring 4.3, if a bean has exactly one constructor, Spring injects its parameters automatically even without writing@Autowired:@Service public class OrderService { private final OrderRepository repository; // Single constructor: @Autowired is optional since Spring 4.3 public OrderService(OrderRepository repository) { this.repository = repository; } }Although field injection (
@Autowired private OrderRepository repository;) looks one line shorter, constructor injection is preferred in real code because fields can be markedfinal(immutable) and unit tests can instantiatenew OrderService(fakeRepository)directly without booting Spring. (If "resource" refers to an external file or URL rather than another bean,@Value("classpath:banner.txt") Resource fileinjects a SpringResource.)Item 3 — Disambiguating candidate beans:
@Qualifier. Suppose two beans implement the samePaymentGatewayinterface. Type-only lookup becomes ambiguous, so Spring fails at startup withNoUniqueBeanDefinitionException("expected single matching bean but found 2"):PaymentGateway (interface) ^ ^ | | StripeGateway PaypalGateway <-- 2 matching beans! ("stripeGateway") ("paypalGateway") | +--- @Qualifier("stripeGateway") ---> CheckoutServiceAdding
@Qualifier("stripeGateway")tells Spring exactly which bean name to wire in:public interface PaymentGateway { void charge(long amountCents); } @Component("stripeGateway") public class StripeGateway implements PaymentGateway { public void charge(long amountCents) { /* ... */ } } @Component("paypalGateway") public class PaypalGateway implements PaymentGateway { public void charge(long amountCents) { /* ... */ } } @Service public class CheckoutService { private final PaymentGateway gateway; public CheckoutService(@Qualifier("stripeGateway") PaymentGateway gateway) { this.gateway = gateway; } }Related options worth knowing: - Mark one implementation
@Primarywhen 90% of callers want a default and only special callers use@Qualifier. - Use@Resource(name = "stripeGateway")(standard Jakarta annotation) to inject directly by bean name. - InjectMap<String, PaymentGateway>orList<PaymentGateway>when the implementation must be chosen dynamically at runtime (for example, based on a user's country in the HTTP request).MySQL DataSource and BeanPropertyRowMapper (Q5–Q6)
Item 6 — MySQL connection abstraction:
DataSource(javax.sql.DataSource).SQLConnector,MySqlConnector, andMySQLJDBCdo not exist in standard Java or Spring; they are distractors.DataSourceis the standard Java interface that acts as a factory for database connections, and every Spring data tool (JdbcTemplate,DataSourceTransactionManager, JPA/Hibernate) takes aDataSource.In production, that
DataSourcebean wraps a connection pool (such asHikariDataSource, Spring Boot's default), which keeps a small set of open TCP/MySQL connections ready to reuse. Borrowing an already-open connection from memory takes under0.1 ms, whereas opening a fresh MySQL connection per query (as test-onlyDriverManagerDataSourcedoes) spends5–20 mson TCP, TLS, and authentication handshakes every single time:@Configuration public class DatabaseConfig { @Bean public DataSource dataSource() { HikariDataSource ds = new HikariDataSource(); ds.setJdbcUrl("jdbc:mysql://localhost:3306/shop"); ds.setUsername("app_user"); ds.setPassword(System.getenv("DB_PASSWORD")); ds.setMaximumPoolSize(10); return ds; } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } }Item 5 — Automatic row-to-object conversion in
JdbcTemplate:BeanPropertyRowMapper. ARowMapperis a small Spring callback interface that converts one row of a JDBCResultSetinto one Java object.BeanPropertyRowMapperautomates this using reflection: it calls the Java bean's no-argument constructor and matches SQL column names to setter methods case-insensitively, automatically convertingsnake_casecolumns intocamelCaseJava properties:SQL ResultSet row: id = 42 first_name = "Ada" email = "ada@example.com" | | | v v v Java setters called: setId(42) setFirstName("Ada") setEmail("ada@example.com")public class Customer { private Long id; private String firstName; private String email; public Customer() {} // required by BeanPropertyRowMapper // standard getters and setters for id, firstName, email } List<Customer> customers = jdbcTemplate.query( "SELECT id, first_name, email FROM customer WHERE country = ?", new BeanPropertyRowMapper<>(Customer.class), "DE");Two practical tips: - Use wrapper types (
Long,Integer) rather than primitives (long,int) for nullable SQL columns, because mapping SQLNULLintosetAge(int)throwsTypeMismatchExceptionby default. - For immutable Javarecords (which have no setters or no-arg constructor), useDataClassRowMapper<>(CustomerRecord.class)(Spring 5.3+), or write a fast lambda(rs, rowNum) -> new CustomerRecord(...)on ultra-high-throughput queries to avoid reflection overhead.Current user in MVC and @PreAuthorize("hasRole(...)") (Q7–Q8)
When a request passes authentication, Spring Security stores the caller's identity inside a
SecurityContext(a per-request security holder bound to the current thread by default). Inside it sits anAuthenticationobject containing the principal (who the user is, typically aUserDetailsorJwtobject) and a collection ofGrantedAuthorityobjects (strings naming what permissions or roles the user holds).Item 7 — Authenticated caller lookup in MVC/REST endpoints: Inject the user directly into the controller method signature with
@AuthenticationPrincipal(or acceptAuthentication/java.security.Principal), or readSecurityContextHolderwhen outside a controller:@RestController public class OrderController { private static final Logger log = LoggerFactory.getLogger(OrderController.class); @GetMapping("/orders") public List<Order> listOrders(@AuthenticationPrincipal UserDetails user) { if (user != null) { log.info("User {} listed orders", user.getUsername()); } return List.of(); } }Watch out for two traps when logging user details: 1. Anonymous endpoints: If an endpoint permits unauthenticated requests, the principal is the plain string
"anonymousUser", so@AuthenticationPrincipal UserDetailsresolves tonull— always null-check before callinguser.getUsername(). 2. Sensitive fields: Log only safe identifiers likeusernameoruserId, never passwords, session cookies, or raw JWT bearer tokens.Item 8 — Role-prefix pitfall in
@PreAuthorize("hasRole('ROLE_ABC')"): In Spring Security, every permission is stored as aGrantedAuthoritystring, and a role is by convention an authority whose string starts with the prefixROLE_:hasRole('ABC')automatically expects theROLE_prefix and checks whether the user holds the authority"ROLE_ABC".hasAuthority('ABC')does no prefixing and checks the exact string"ABC".
Compare what happens across different stored authorities:
User's stored GrantedAuthority hasRole('ABC') hasRole('ROLE_ABC') hasAuthority('ABC') ------------------------------ -------------- ------------------- ------------------- "ROLE_ABC" GRANTED GRANTED (SpEL 4+) DENIED "ABC" (missing ROLE_ prefix!) DENIED DENIED GRANTED "ROLE_abc" (lowercase!) DENIED DENIED DENIEDWhy
@PreAuthorize("hasRole('ROLE_ABC')")results in access denied (or errors) in real applications: 1. Prefix conventions and doubled prefixes:hasRoleis designed to add"ROLE_"automatically. In Java configuration builders (User.withUsername(...).roles("ROLE_ABC")orauthorizeHttpRequests(...).hasRole("ROLE_ABC")), passing"ROLE_ABC"actually throwsIllegalArgumentExceptionbecause"ROLE_"is inserted automatically, and in custom or legacy prefixers that blindly prepend"ROLE_",hasRole('ROLE_ABC')looks for"ROLE_ROLE_ABC", which nobody has! 2. Authorities loaded without"ROLE_": Even though@PreAuthorizeSpEL expressions in modern Spring Security tolerate a leadingROLE_without doubling it,hasRole(...)still requires the user'sGrantedAuthorityto be"ROLE_ABC". If your database or JWT mapper creatednew SimpleGrantedAuthority("ABC")(orSCOPE_ABC),hasRoledenies access with HTTP403 Forbidden.Correct usage: - When using roles (stored as
ROLE_ABC), omit the prefix inhasRole: ```java // User builder automatically stores "ROLE_ABC" UserDetails user = User.withUsername("ann") .password("{bcrypt}$2a$10$...") .roles("ABC") .build();@PreAuthorize("hasRole('ABC')") // Idiomatic: checks for "ROLE_ABC" public void approveRefund(long orderId) { /* ... / }
- When your database or token stores raw permission names **without** `ROLE_` (such as `"ABC"`), use `hasAuthority` instead:java @PreAuthorize("hasAuthority('ABC')") // Exact match for "ABC", no prefix added public void approveRefund(long orderId) { / ... */ }`` - Finally, remember to enable method-level annotations with@EnableMethodSecurityon a@Configurationclass — without it,@PreAuthorize` is completely inactive!
Intuition & how it works
Think of the Spring Framework as the operations manager of a well-run restaurant kitchen. At opening time, the manager reads all recipe binders once, hires one chef per station, and connects them (IoC container and dependency injection). A bouncer at the door checks each guest's wristband and clips their name badge onto their jacket (Spring Security), a clipboard auditor standing outside each station writes down incoming orders before cooking starts (AOP @Before advice), and a shared rack of pre-warmed phone lines plus a standardized order slip (DataSource pool and BeanPropertyRowMapper) handles all database calls cleanly.
If you skip these patterns and wire everything manually, every method ends up calling new to create its own helpers and database connections, copying authentication checks and log.info(...) lines into business logic, and unpacking SQL columns field by field. Under real traffic, creating fresh containers or unpooled connections per request exhausts MySQL sockets within seconds, mixing logging and security into business methods creates blind spots when someone forgets a check, and unit-testing a service becomes painful because dependencies are hardcoded inside it.
Walk through one concrete request — user "ann" (holding authority "ROLE_ABC") calling GET /orders — to see all eight answers working together:
- Startup (Questions 1, 3, 4, 6): One shared
ApplicationContextloads all config files once, creates a pooledDataSource(10warm MySQL connections), wiresJdbcTemplate, and injects@Qualifier("stripeGateway")andOrderRepositoryintoOrderServicevia constructor injection. - Security & Controller (Questions 7, 8): Spring Security authenticates
"ann", storesUserDetails("ann", [ROLE_ABC])inSecurityContext, and passesuserintolistOrders(@AuthenticationPrincipal UserDetails user)so the controller logs"User ann listed orders". - Proxy checks (Questions 2, 8): When the controller calls
orderService.findOrders("ann"), the Spring proxy first evaluates@PreAuthorize("hasRole('ABC')")(matching"ROLE_ABC") and then runs@Beforeadvice to auditargs=[ann]before the method body starts. - Database query (Questions 5, 6):
JdbcTemplateborrows 1 connection fromDataSource, runsSELECT id, first_name FROM customer, andBeanPropertyRowMappermapsid -> setId(...)andfirst_name -> setFirstName(...)automatically.
Key points
- One shared IoC container (Q1): Inversion of Control (IoC) means Spring creates and wires objects (beans) for you. Pass all config files or
@Configurationclasses to a singleClassPathXmlApplicationContextorAnnotationConfigApplicationContextonce at startup so singleton beans and connection pools are shared across the entire app. @Beforefor auditing arguments (Q2): Aspect-Oriented Programming (AOP) attaches cross-cutting logic via a proxy (an auto-generated wrapper around a bean).@Beforeruns prior to every call regardless of whether the method later throws an exception, reads original arguments viaJoinPoint.getArgs(), and cannot accidentally swallow return values like@Aroundcan.- Disambiguating and injecting beans (Q3, Q4):
@Autowiredinjects dependencies by type (and is optional on single-constructor classes since Spring 4.3). When multiple beans implement one interface,@Qualifier("beanName")selects a specific bean and avoidsNoUniqueBeanDefinitionException. DataSourceandBeanPropertyRowMapper(Q5, Q6):javax.sql.DataSourceis the standard JDBC connection factory (backed in production by a connection pool likeHikariDataSourcethat reuses open sockets).BeanPropertyRowMappermaps SQL columns (includingsnake_caselikefirst_name) to JavaBeancamelCasesetters (setFirstName) via reflection.- Current user and
hasRoleconventions (Q7, Q8): Spring Security stores the caller's identity (principal) and permissions (GrantedAuthoritystrings) inSecurityContext. Read the user via@AuthenticationPrincipal,Principal/Authenticationparameters, orSecurityContextHolder.hasRole('ABC')checks for the prefixed authority"ROLE_ABC", whereashasAuthority('ABC')checks the exact string"ABC"with no prefix.
Common mistakes
- Instantiating
new ClassPathXmlApplicationContext(...)inside request handlers: Every call builds a separate container with duplicate singletons and connection pools (16containers ×10pooled connections =160connections, exceeding MySQL's default151limit). - Choosing
@AfterReturningfor security or audit logs: Calls that throw exceptions — often the exact failed or malicious requests auditors care about most — never trigger@AfterReturningand vanish from the logs. - Expecting
@Before,@Transactional, or@PreAuthorizeto fire onthis.otherMethod(): Internal self-calls stay inside the raw Java object and never pass through the outer Spring proxy, so advice and security checks are silently skipped. - Relying on variable names instead of
@Qualifier: Naming a parameterstripeGatewayhappens to match bean"stripeGateway"as a fallback, but a harmless IDE variable rename immediately breaks startup withNoUniqueBeanDefinitionException. - Mapping nullable SQL columns into primitive fields (
long,int) withBeanPropertyRowMapper: A SQLNULLtriggersTypeMismatchException; always use boxed wrapper types (Long,Integer) when a column can beNULL. - Using
DriverManagerDataSourcein production: UnlikeHikariDataSource, it does not pool connections and opens a brand-new TCP/MySQL connection on every single query. - Mixing up
hasRoleandhasAuthority(or forgetting@EnableMethodSecurity): If user permissions are loaded from a database as"ABC"without"ROLE_",hasRole('ABC')andhasRole('ROLE_ABC')both fail with403because both look for"ROLE_ABC". Worse, forgetting@EnableMethodSecurityleaves@PreAuthorizecompletely inert so every caller gets through.
Follow-up questions
- How would you record both execution latency and call outcome in the same AOP audit entry? Switch from
@Beforeto@Around, which wraps both sides of the method call usingProceedingJoinPoint. RecordSystem.nanoTime()before callingpjp.proceed(), return the result unchanged, and write the audit log inside afinallyblock so elapsed time and pass/fail status are recorded even when the target method throws an exception. - Why are proxy-based annotations skipped when one method calls another method inside the same bean? Spring AOP wraps each bean in a runtime proxy, so interception only occurs when a caller invokes the bean through that outer proxy reference. When
methodA()callsthis.methodB(), execution goes straight to the underlying object and skips the proxy completely; fix this by extractingmethodB()into a separate collaborator bean (or enabling AspectJ compile-time/load-time bytecode weaving). - When is PreAuthorize preferable to Secured for method-level access control in Spring Security?
@Secured("ROLE_ABC")only checks static authority string literals and cannot evaluate dynamic conditions or method arguments.@PreAuthorizeevaluates full Spring Expression Language (SpEL) expressions, letting you combine roles and inspect parameters such as@PreAuthorize("hasRole('ADMIN') or #orderId != null and @authz.isOwner(#orderId, authentication.name)").
Follow-up questions
- How would you record both execution latency and call outcome in the same AOP audit entry?
- Why are proxy-based annotations skipped when one method calls another method inside the same bean?
- When is PreAuthorize preferable to Secured for method-level access control in Spring Security?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes