Spring Boot is an open-source Java-based framework used to create stand-alone, production-grade Spring-based applications with minimal configuration.
You can create a Spring Boot project using:
Example using Spring Boot CLI:
spring init --dependencies=web,data-jpa my-project
cd my-project
@SpringBootApplication
: Combines @Configuration
, @EnableAutoConfiguration
, and @ComponentScan
@Configuration
: Indicates that a class declares one or more @Bean
methods@EnableAutoConfiguration
: Enables Spring Boot's auto-configuration mechanism@ComponentScan
: Tells Spring to look for components in the current package and its sub-packages@Controller
: Marks the class as a web controller@RestController
: Combines @Controller
and @ResponseBody
@RequestMapping
: Maps HTTP requests to handler methods@GetMapping
, @PostMapping
, @PutMapping
, @DeleteMapping
: Shortcut for @RequestMapping
with a specific HTTP methodExample:
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<User> getAllUsers() {
// Implementation
}
}
@Entity
: Specifies that the class is an entity and is mapped to a database table@Repository
: Indicates that the class is a repository@Service
: Indicates that the class is a service@Autowired
: Marks a constructor, field, or setter method to be autowired by Spring's dependency injectionExample:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
// getters and setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
// methods
}
Spring Boot uses application.properties
or application.yml
for configuration.
Example application.properties
:
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
Profiles allow you to define environment-specific configurations.
Example:
# application-dev.properties
server.port=8080
# application-prod.properties
server.port=80
Activate a profile:
java -jar myapp.jar --spring.profiles.active=prod
You can create custom configuration classes:
@Configuration
public class MyConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
Spring Data JPA simplifies data access layer implementation.
Example:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByLastName(String lastName);
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(User user) {
return userRepository.save(user);
}
public List<User> getUsersByLastName(String lastName) {
return userRepository.findByLastName(lastName);
}
}
Create RESTful APIs easily with Spring Boot.
Example:
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
}
Use @ControllerAdvice
for global exception handling:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<?> handleUserNotFoundException(UserNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
Use @SpringBootTest
for integration tests:
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void testCreateUser() {
User user = new User("John Doe");
User savedUser = userService.createUser(user);
assertNotNull(savedUser.getId());
assertEquals("John Doe", savedUser.getName());
}
}
Test your controllers using MockMvc:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void testGetAllUsers() throws Exception {
List<User> users = Arrays.asList(new User("John"), new User("Jane"));
when(userService.getAllUsers()).thenReturn(users);
mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].name", is("John")))
.andExpect(jsonPath("$[1].name", is("Jane")));
}
}
Spring Boot Actuator provides production-ready features to help you monitor and manage your application.
Add the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Some useful actuator endpoints:
/actuator/health
: Shows application health information/actuator/info
: Displays arbitrary application info/actuator/metrics
: Shows metrics information/actuator/env
: Exposes properties from Spring's ConfigurableEnvironmentCreate a custom health indicator:
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int errorCode = check();
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
private int check() {
// Perform some specific health check
return 0;
}
}
Add the security starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Configure basic authentication:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
Example of constructor injection:
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// Service methods
}
2024 © All rights reserved - buraxta.com