我将为你详细介绍Spring Boot框架,涵盖其核心概念、关键技术,并结合应用实例展示开发过程,帮助你快速掌握并应用于实际项目。
Spring Boot是由Pivotal团队开发的一个基于Spring框架的全新框架,其设计目的是为了简化新Spring应用的初始搭建以及开发过程。它通过提供默认配置、内嵌式容器等,让开发者能够快速构建独立的、生产级别的基于Spring的应用程序。
@EnableAutoConfiguration
注解开启此功能,该注解会导入AutoConfigurationImportSelector
类,扫描类路径下JAR文件,并加载META - INF/spring.factories
文件中定义的自动配置类。这些自动配置类依据条件注解(如@ConditionalOnClass
、@ConditionalOnMissingBean
等)决定是否加载相应的Bean,极大减少了开发者编写配置代码的工作量。Spring Initializr是一个在线工具,可帮助快速生成Spring Boot项目初始代码。打开https://start.spring.io/
,在页面中可进行如下操作:
mysql - connector - j
和Spring Data JPA的spring - boot - starter - data - jpa
)。解压后的项目目录结构如下:
com.example.demo
包用于存放项目相关代码。以创建一个简单的RESTful API服务为例:
src/main/java/com.example.demo
包下创建实体类,如User.java
:public class User {
private Long id;
private String name;
private String email;
// 生成getter和setter方法
}
UserRepository.java
:import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
UserController.java
处理HTTP请求:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userRepository.save(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
}
}
@SpringBootApplication
注解,该注解包含了@EnableAutoConfiguration
、@ComponentScan
等多个注解功能,开启Spring Boot自动配置和组件扫描等功能。例如DemoApplication.java
:import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Spring Boot支持多种配置文件格式,如.properties和.yml。以application.yml为例,常见配置如下:
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root
driver - class - name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl - auto: update
show - sql: true
其中spring.jpa.hibernate.ddl - auto=update
表示Hibernate会在启动时自动创建或更新表结构,spring.jpa.show - sql=true
表示在控制台打印SQL语句,方便调试。
DemoApplication
的main
方法。mvn spring - boot:run
(Maven项目)或gradle bootRun
(Gradle项目)。项目启动后,可使用工具(如Postman)访问http://localhost:8081/api/users
测试API功能,如发送GET请求获取用户列表,发送POST请求创建新用户等。
本案例构建一个客户关系管理系统,涵盖客户管理、销售管理、服务管理、数据分析、系统管理等多个模块,以满足企业对客户关系管理的需求,具备良好的可扩展性和可维护性。
创建以下主要数据库表:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
@PostMapping("/add")
public String addCustomer(@RequestBody Customer customer) {
return customerService.addCustomer(customer);
}
@PutMapping("/update")
public String updateCustomer(@RequestBody Customer customer) {
return customerService.updateCustomer(customer);
}
@DeleteMapping("/delete/{id}")
public String deleteCustomer(@PathVariable Long id) {
return customerService.deleteCustomer(id);
}
@GetMapping("/list")
public List<Customer> getCustomerList(@RequestParam(required = false) String keyword) {
return customerService.getCustomerList(keyword);
}
@GetMapping("/{id}")
public Customer getCustomerById(@PathVariable Long id) {
return customerService.getCustomerById(id);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CustomerService {
@Autowired
private CustomerMapper customerMapper;
public String addCustomer(Customer customer) {
try {
customerMapper.addCustomer(customer);
return "添加成功";
} catch (Exception e) {
e.printStackTrace();
return "添加失败";
}
}
public String updateCustomer(Customer customer) {
try {
customerMapper.updateCustomer(customer);
return "更新成功";
} catch (Exception e) {
e.printStackTrace();
return "更新失败";
}
}
public String deleteCustomer(Long id) {
try {
customerMapper.deleteCustomer(id);
return "删除成功";
} catch (Exception e) {
e.printStackTrace();
return "删除失败";
}
}
public List<Customer> getCustomerList(String keyword) {
if (keyword!= null &&!keyword.isEmpty()) {
return customerMapper.getCustomerListByKeyword(keyword);
} else {
return customerMapper.getCustomerList();
}
}
public Customer getCustomerById(Long id) {
return customerMapper.getCustomerById(id);
}
}
<mapper namespace="com.example.crm.mapper.CustomerMapper">
<insert id="addCustomer" parameterType="Customer">
INSERT INTO customer (name, gender, age, contact_info, address, create_time, create_user)
VALUES (#{name}, #{gender}, #{age}, #{contactInfo}, #{address}, #{createTime}, #{createUser})
insert>
<update id="updateCustomer" parameterType="Customer">
UPDATE customer
SET name = #{name}, gender = #{gender}, age = #{age}, contact_info = #{contactInfo}, address = #{address},
update_time = #{updateTime}, update_user = #{updateUser}
WHERE id = #{id}
update>
<delete id="deleteCustomer" parameterType="long">
DELETE FROM customer WHERE id = #{id}
delete>
<select id="getCustomerList" resultType="Customer">
SELECT * FROM customer
select>
<select id="getCustomerListByKeyword" resultType="Customer">
SELECT * FROM customer WHERE name LIKE CONCAT('%', #{keyword}, '%') OR contact_info LIKE CONCAT('%', #{keyword}, '%')
select>
<select id="getCustomerById" resultType="Customer">
SELECT * FROM customer WHERE id = #{id}
select>
mapper>
Spring Boot框架凭借其强大的自动配置、独立运行、内嵌容器等特性,极大地简化了Spring应用开发过程,提高了开发效率和应用的可维护性。通过实际案例,我们展示了如何从项目创建、业务代码编写、配置文件设置到最终部署和测试的完整开发流程。在未来的开发中,Spring Boot将持续发展,与更多新技术(如微服务架构、云原生技术等)深度融合,为开发者提供更高效、便捷的开发体验,助力构建更强大、稳定的应用系统。
如果你在学习过程中对Spring Boot框架的某个部分存在疑问,或者希望看到更多
代码获取方式
https://pan.quark.cn/s/14fcf913bae6
关注我获取更多内容