Spring Framework
Java's most popular enterprise framework
🌱 What is Spring Framework?
Spring Framework is a comprehensive Java platform that provides infrastructure support for developing robust applications. It simplifies enterprise Java development through dependency injection, aspect-oriented programming, and extensive integration capabilities.
// Simple Spring Bean example
@Component
public class HelloService {
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
Core Spring Concepts
Dependency Injection
Automatic object creation and wiring
@Autowired
private UserService userService;
IoC Container
Manages object lifecycle and dependencies
@Configuration
@ComponentScan
public class AppConfig {}
AOP
Aspect-Oriented Programming support
@Aspect
@Component
public class LoggingAspect {}
Annotations
Configuration through annotations
@Service
@Repository
@Controller
🔹 Basic Spring Application
Here's a simple Spring application structure:
// Main Application Class
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
// Service Class
@Service
public class UserService {
public User findUser(Long id) {
return new User(id, "John Doe");
}
}
// Controller Class
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
return userService.findUser(id);
}
}
Output:
GET /user/1 → {"id": 1, "name": "John Doe"}
🔹 Spring Configuration
Configure Spring using Java-based configuration:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class WebConfig {
@Bean
public DataSource dataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:h2:mem:testdb");
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
🔹 Spring Annotations
Common Spring annotations for beginners:
// Component Annotations
@Component // Generic component
@Service // Business logic layer
@Repository // Data access layer
@Controller // Web layer
// Dependency Injection
@Autowired // Inject dependencies
@Qualifier // Specify which bean to inject
@Value // Inject property values
// Configuration
@Configuration // Configuration class
@Bean // Define a bean
@ComponentScan // Scan for components