本文介绍了Spring Boot企业级开发学习的全过程,从快速入门到实战案例,涵盖项目搭建、配置、常用功能、安全配置以及性能优化等多个方面,旨在帮助开发者全面掌握Spring Boot企业级开发技能。Spring Boot企业级开发学习包括了从创建第一个Spring Boot项目到搭建和配置Spring Boot应用,再到实现RESTful接口和数据库操作等功能。
Spring Boot是一个基于Spring框架的、轻量级的开发框架,旨在简化Spring应用的初始搭建及开发过程。Spring Boot可以让开发者专注于业务逻辑而非基础设施的配置,提供了一套约定优于配置的原则,极大简化了项目的启动过程和配置步骤。
创建一个简单的Spring Boot项目来了解其基本用法。
@SpringBootApplication
注解,启用自动配置。import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } }
启动应用,使用IDEA中的Spring Boot运行器启动项目或者使用命令行执行mvn spring-boot:run
。
http://localhost:8080/hello
,可以看到返回“Hello, World!”。Spring Boot使用application.properties
或application.yml
作为配置文件,可以覆盖默认配置。
# server configuration server.port=8080 server.tomcat.uri-encoding=UTF-8 # database configuration spring.datasource.url=jdbc:mysql://localhost:3306/dbname spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # logging configuration logging.level.root=INFO logging.file.name=app.log
server: port: 8080 tomcat: uri-encoding: UTF-8 spring: datasource: url: jdbc:mysql://localhost:3306/dbname username: root password: root driver-class-name: com.mysql.jdbc.Driver logging: level: root: INFO file: name: app.log
使用Spring Boot配置数据库连接,可以使用JdbcTemplate
进行简单的SQL操作。
在application.properties
或application.yml
中配置数据源。
spring.datasource.url=jdbc:mysql://localhost:3306/dbname spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private JdbcTemplate jdbcTemplate; public void insertUser(String name, String email) { jdbcTemplate.update("INSERT INTO users(name, email) VALUES (?, ?)", name, email); } public List<User> getAllUsers() { return jdbcTemplate.query("SELECT id, name, email FROM users", new UserMapper()); } }
Spring Boot使用@RestController
注解来创建RESTful接口。
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserRestController { @GetMapping("/users") public List<User> getAllUsers() { // 模拟数据 List<User> users = new ArrayList<>(); users.add(new User("John Doe", "john@example.com")); users.add(new User("Jane Doe", "jane@example.com")); return users; } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mybatis</artifactId> </dependency>
import org.apache.ibatis.annotations.Select; public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User getUserById(int id); }
mybatis.mapper-locations=classpath:mapper/*.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String email; // 省略getter和setter }
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Integer> { }
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency>
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @RestController public class FileController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { Path root = Paths.get("uploads"); Files.createDirectories(root); Files.write(root.resolve(file.getOriginalFilename()), file.getBytes()); return "File uploaded successfully"; } catch (IOException e) { e.printStackTrace(); } } return "File upload failed"; } }
import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.net.MalformedURLException; @RestController public class FileController { @GetMapping("/download/{filename}") public ResponseEntity<Resource> downloadFile(@PathVariable String filename) throws MalformedURLException { Path root = Paths.get("uploads"); Resource resource = new UrlResource(root.resolve(filename).toUri()); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } }
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String email; // 省略getter和setter }
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Integer> { }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class UserService { @Autowired private UserRepository userRepository; @Transactional public User addUser(User user) { return userRepository.save(user); } public List<User> getAllUsers() { return userRepository.findAll(); } public User getUserById(int id) { return userRepository.findById(id).orElse(null); } @Transactional public User updateUser(User user) { User existingUser = userRepository.findById(user.getId()).orElse(null); if (existingUser != null) { existingUser.setName(user.getName()); existingUser.setEmail(user.getEmail()); return userRepository.save(existingUser); } return null; } @Transactional public void deleteUser(int id) { userRepository.deleteById(id); } }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> getAllUsers() { return userService.getAllUsers(); } @PostMapping public User addUser(@RequestBody User user) { return userService.addUser(user); } @GetMapping("/{id}") public User getUserById(@PathVariable int id) { return userService.getUserById(id); } @PutMapping("/{id}") public User updateUser(@PathVariable int id, @RequestBody User user) { return userService.updateUser(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable int id) { userService.deleteUser(id); } }
mvn clean package
target
目录下,可以使用命令行方式启动。java -jar target/myapp.jar
编写Dockerfile。
FROM openjdk:11 VOLUME /tmp COPY target/myapp.jar app.jar ENTRYPOINT ["java","-jar","/app.jar"]
构建并运行Docker镜像。
docker build -t myapp . docker run -p 8080:8080 myapp
使用Spring Boot默认的日志配置,可以在application.properties
中配置日志级别和输出位置。
logging.level.root=INFO logging.file.name=app.log
添加spring-boot-starter-actuator
依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
启用Actuator端点。
management.endpoints.web.exposure.include=*
访问http://localhost:8080/actuator
可以看到一系列监控端点。
添加spring-boot-starter-security
依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
配置安全。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .and() .httpBasic(); } @Override @Bean public UserDetailsService userDetailsService() { var user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }
使用Spring Security进行认证。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .and() .httpBasic(); } @Override @Bean public UserDetailsService userDetailsService() { var user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }
配置CORS。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
通过Spring Boot Actuator监控常见性能指标。
management.endpoints.web.exposure.include=health,info,mappings,beans,env,info,metrics
添加spring-boot-starter-actuator
依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
启用Actuator端点。
management.endpoints.web.exposure.include=*
访问http://localhost:8080/actuator
可以看到监控端点,例如/actuator/metrics
、/actuator/health
等。
使用Spring Boot默认的日志配置,可以在application.properties
中配置日志级别和输出位置。
logging.level.root=INFO logging.file.name=app.log
在代码中使用@Slf4j
注解引入日志。
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private static final Logger log = LoggerFactory.getLogger(UserController.class); @GetMapping("/users") public List<User> getAllUsers() { log.info("Getting all users"); // 获取用户列表 return userService.getAllUsers(); } }
通过日志输出来跟踪和调试代码。
以上内容涵盖了Spring Boot从入门到实战的各个方面,通过实践示例和代码演示,希望对您学习Spring Boot有所帮助。