βœ… 1. What is Spring Framework?

Spring is a powerful, lightweight framework for building Java enterprise applications. It promotes loose coupling through Dependency Injection (DI) and offers powerful integrations for web apps, data access, security, AOP, and more.

πŸ”‘ Core Features:

  • IoC Container (Dependency Injection)
  • AOP (Aspect-Oriented Programming)
  • Spring MVC (Web framework)
  • Spring JDBC/ORM
  • Transaction Management
  • Spring Security
  • Spring Testing

βœ… 2. Dependency Injection (DI) in Spring

➀ What is Dependency Injection?

DI is a design pattern that allows an object to receive its dependencies from an external source rather than creating them itself.

✨ Benefits:

  • Loose coupling
  • Better testability
  • More maintainable code

➀ DI with XML Configuration

πŸ“„ beans.xml:

Explanation:

  • Declares 2 beans.
  • employeeService depends on employeeDao.
  • <property> injects employeeDao into employeeService using its setter method.
<bean id="employeeDao" class="com.app.EmployeeDao" />
<bean id="employeeService" class="com.app.EmployeeService">
<property name="employeeDao" ref="employeeDao" />
</bean>

πŸ“„ EmployeeService.java:

Explanation:

  • setEmployeeDao() is a setter.
  • Spring calls this and injects the dependency defined in beans.xml.
public class EmployeeService {
private EmployeeDao employeeDao;

public void setEmployeeDao(EmployeeDao dao) {
this.employeeDao = dao;
}
}

πŸ”Ή Annotation-Based DI

πŸ“„ EmployeeDao.java

@Component
public class EmployeeDao {}

πŸ“„ EmployeeService.java

@Service
public class EmployeeService {
@Autowired
private EmployeeDao employeeDao;
}

πŸ“„ AppConfig.java

@Configuration
@ComponentScan("com.app")
public class AppConfig {}

Explanation:

  • @Component/@Service: Marks the class as a Spring-managed bean.
  • @Autowired: Automatically wires EmployeeDao into EmployeeService.
  • @ComponentScan: Scans the package for Spring annotations.

βœ… 3. Bean Scopes in Spring

ScopeDescription
singletonOne shared instance per Spring container
prototypeNew instance each time it’s requested
requestOne per HTTP request (Web only)
sessionOne per session (Web only)

πŸ“„ Example:

Explanation:

  • @Component: Declares the class as a bean.
  • @Scope("prototype"): Spring will create a new instance every time this bean is requested (instead of sharing the same one).
@Component
@Scope("prototype")
public class MyBean {}

βœ… 4. Aspect-Oriented Programming (AOP)

➀ What is AOP?

AOP allows you to define cross-cutting concerns (like logging, security, transactions) separately from business logic.

πŸ“„ Example: Logging Aspect

@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.app.service.*.*(..))")
public void log(JoinPoint jp) {
System.out.println("Method called: " + jp.getSignature());
}
}

Key Annotations:

  • @Aspect
  • @Before, @After, @Around
  • @EnableAspectJAutoProxy

Explanation:

  • @Aspect: Declares this class as an AOP aspect.
  • @Before(...): Executes before any method in com.app.service.* package.
  • JoinPoint: Gives method metadata at runtime.
  • This is commonly used for logging, auditing, security.

βœ… 5. Spring JDBC (with JdbcTemplate)

➀ What is JdbcTemplate?

A helper class that simplifies database operations.

πŸ“„ UserDao.java:

@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbc;

public void save(User u) {
jdbc.update("INSERT INTO users(name,email) VALUES (?,?)", u.getName(), u.getEmail());
}
}

πŸ“„ DataSource Config:

@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setUrl("jdbc:mysql://localhost/test");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}

Explanation:

  • JdbcTemplate handles low-level JDBC tasks (connection, statement, exception).
  • jdbc.update(...): Runs a SQL update/insert.
  • ?: Placeholder for values.
  • DataSource: Provides database connection details.

βœ… 6. Spring MVC – Web Framework

➀ DispatcherServlet Flow:

Request β†’ DispatcherServlet β†’ Controller β†’ ViewResolver β†’ JSP

πŸ“„ HomeController.java:

@Controller
public class HomeController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("msg", "Hello from Spring!");
return "hello";
}
}

πŸ“„ hello.jsp:

<h2>${msg}</h2>

Explanation:

  • @Controller: Marks the class as a Spring MVC controller.
  • @RequestMapping("/hello"): Maps URL /hello to this method.
  • Model model: Sends data to the view.
  • model.addAttribute(...): Adds data to be shown in JSP.
  • JSP renders the msg value from the controller.

βœ… 7. Form Handling in Spring MVC

πŸ“„ User.java:

public class User {
private String name;
private String email;
// Getters and setters
}

πŸ“„ UserController.java:

@GetMapping("/register")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "register";
}

@PostMapping("/save")
public String save(@ModelAttribute("user") User user) {
System.out.println(user.getName() + " - " + user.getEmail());
return "result";
}

πŸ“„ register.jsp:

<form action="save" method="post">
Name: <input name="name" type="text"/><br/>
Email: <input name="email" type="text"/><br/>
<input type="submit"/>
</form>

Explanation:

  • @ModelAttribute("user"): Binds form fields to User object.
  • GET /register: Shows form with an empty User object.
  • POST /save: Submits form, Spring populates the User object.

βœ… 8. Spring Transaction Management

πŸ“„ BankService.java:

@Service
public class BankService {
@Autowired
private AccountDao dao;

@Transactional
public void transfer(String fromAcc, String toAcc, double amount) {
dao.withdraw(fromAcc, amount);
dao.deposit(toAcc, amount);
}
}

πŸ’‘ If any method fails, the transaction is rolled back.

Explanation:

  • @Transactional: Spring wraps this method in a transaction.
  • If withdraw succeeds but deposit fails, everything rolls back.
  • Ensures atomicity and consistency.

βœ… 9. Spring Security (In-Memory Auth)

πŸ“„ SecurityConfig.java:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}1234").roles("ADMIN");
}

protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().formLogin();
}
}

πŸ”’ Add spring-security-web and spring-security-config to your dependencies.

Explanation:

  • @EnableWebSecurity: Enables Spring Security.
  • inMemoryAuthentication(): Hardcoded login (admin/1234).
  • {noop}: Tells Spring the password is plaintext (for demo only).
  • http.authorizeRequests(): Protects all endpoints β€” forces login.

βœ… 10. Spring Profiles (For Environment Configs)

πŸ“„ DevConfig.java:

@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public DataSource devDataSource() { ... }
}

πŸ“„ ProdConfig.java:

@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public DataSource prodDataSource() { ... }
}

πŸ“„ application.properties:

propertiesCopyEditspring.profiles.active=dev

Explanation:

  • @Profile("dev"): Used only when dev profile is active.
  • Switch between environments without changing code.

βœ… 11. Spring Testing with JUnit

πŸ“„ UserServiceTest.java:

Explanation:

  • @RunWith: Integrates Spring context with JUnit.
  • @ContextConfiguration: Loads beans from AppConfig.
  • @Autowired: Injects the bean under test.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class UserServiceTest {

@Autowired
private UserService userService;

@Test
public void testSave() {
User u = new User("Test", "[email protected]");
userService.save(u);
}
}

βœ… 12. Spring Best Practices

Best PracticeWhy?
Use constructor injectionPromotes immutability and testing
Keep controller thin, service richFollows separation of concerns
Avoid field injection if possibleHarder to test
Externalize configurationEasier environment management
Use @Service, @Repository properlyHelps AOP and Spring’s stereotypes
Use @Transactional at service layerControls transaction scope cleanly

🧠 Spring Interview Q&A Summary

QuestionAnswer
What is Spring?A modular Java framework for enterprise applications
What is DI?Injecting dependencies instead of creating them manually
Singleton vs Prototype?Singleton = 1 bean instance, Prototype = new bean every time
What is AOP?Separates cross-cutting concerns
Purpose of @Transactional?Rollback changes if something fails
Difference: @Component vs @Service?@Service is semantic for business layer
What is Spring MVC flow?DispatcherServlet β†’ Controller β†’ ViewResolver β†’ JSP
JdbcTemplate benefits?Simplifies DB access
XML vs Java Config?Java Config is type-safe and more modern
Profiles use case?Environment-specific beans (dev/test/prod)

βœ… Additional Concepts of Spring

πŸ”Ή 1. Bean Lifecycle Callbacks

  • init-method / destroy-method in XML
  • @PostConstruct and @PreDestroy in annotation config

πŸ“„ Example:

@Component
public class MyBean {

@PostConstruct
public void init() {
System.out.println("Bean initialized");
}

@PreDestroy
public void destroy() {
System.out.println("Bean destroyed");
}
}

πŸ“Œ Useful for initializing resources or cleanup.

πŸ”Ή 2. FactoryBean Interface

Allows more complex logic when creating beans.

πŸ“„ Example:

public class CarFactory implements FactoryBean<Car> {
public Car getObject() {
return new Car(); // Complex creation logic
}
public Class<?> getObjectType() {
return Car.class;
}
}

Used when bean creation needs dynamic logic.

πŸ”Ή 3. ApplicationContext vs BeanFactory

FeatureBeanFactoryApplicationContext
Lazy loadingYesNo (eager by default)
Event handlingNoYes
InternationalizationNoYes

Use ApplicationContext in most cases.

πŸ”Ή 4. Spring Events

Spring lets beans communicate via events.

πŸ“„ Example:

public class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}

@Component
public class MyListener implements ApplicationListener<MyEvent> {
public void onApplicationEvent(MyEvent event) {
System.out.println("Event received!");
}
}

πŸ“Œ Good for decoupled communication within app.

πŸ”Ή 5. Custom Qualifiers

When multiple beans of the same type exist.

πŸ“„ Example:

@Qualifier("mysqlRepo")
@Autowired
private UserRepository repo;

Or define a custom qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
public @interface MyRepo {}

πŸ”Ή 6. BeanPostProcessor

Custom logic before and after bean initialization.

πŸ“„ Example:

public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String name) {
System.out.println("Before Init: " + name);
return bean;
}

public Object postProcessAfterInitialization(Object bean, String name) {
System.out.println("After Init: " + name);
return bean;
}
}

πŸ”Ή 7. Property Placeholder / External Properties

Reading values from .properties files.

πŸ“„ Example:

db.url=jdbc:mysql://localhost/test

πŸ“„ Java Config:

@PropertySource("classpath:db.properties")
public class AppConfig {
@Value("${db.url}")
private String url;
}

πŸ”Ή 8. @Required Annotation

Forcing Spring to inject a property (setter-based injection).

@Required
public void setName(String name) {
this.name = name;
}

πŸ’‘ Deprecated in later Spring versions β€” use constructor injection.

πŸ”Ή 9. Spring Integration with Hibernate

Using HibernateTemplate, LocalSessionFactoryBean, or Spring ORM.

πŸ“„ XML example:

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
...
</bean>

10. 🧠 SpEL (Spring Expression Language)

. @value

@Value("#{2 * 2}")
private int value;
  • @Scheduled
Scheduled(fixedRate = 5000)
public void poll() {
System.out.println("Polling...");
}
  • @Cacheable
@Cacheable("users")
public User findById(String id) {
...
}

Similar Posts