提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
Spring Boot简化Spring应用开发,有自动配置等特性。Web开发基于HTTP协议,其项目常采分层架构,Controller处理请求,Service实现业务,Dao操作数据库,各层职责清晰,利于开发维护 。
Spring Boot通过自动配置和起步依赖简化开发,核心特点:
入门步骤:
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(String name) {
return "Hello " + name + "~";
}
}
http://localhost:8080/hello?name=World
Spring Boot通过条件注解(如@ConditionalOnClass
)实现自动配置:
@SpringBootApplication
包含:
@SpringBootConfiguration
:声明配置类@EnableAutoConfiguration
:启用自动配置@ComponentScan
:扫描启动类所在包及其子包自动配置流程:
META-INF/spring.factories
中的自动配置类@ConditionalOnMissingBean
)决定是否生效示例:自动配置Tomcat服务器:
@ConditionalOnClass({ Servlet.class, Tomcat.class })
@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
public class TomcatServletWebServerFactoryAutoConfiguration {
// 配置Tomcat相关Bean
}
请求协议结构:
GET /hello?name=World HTTP/1.1
Host: localhost:8080
Accept: text/html
响应协议结构:
HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
Content-Length: 11
Hello World~
代码示例:获取请求信息
@RestController
public class RequestController {
@RequestMapping("/request")
public String handleRequest(HttpServletRequest request) {
System.out.println("Method: " + request.getMethod());
System.out.println("URI: " + request.getRequestURI());
System.out.println("Header: " + request.getHeader("Accept"));
return "OK";
}
}
@Controller
和@ResponseBody
示例:返回JSON数据
@RestController
public class UserController {
@RequestMapping("/user")
public User getUser() {
return new User("Alice", 25);
}
}
class User {
private String name;
private int age;
// 构造方法、getter/setter省略
}
分层设计:
示例:分层代码结构
// Controller层
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/users")
public List<User> getUsers() {
return userService.getAllUsers();
}
}
// Service层
@Service
public class UserService {
@Autowired
private UserDao userDao;
public List<User> getAllUsers() {
return userDao.findAll();
}
}
// Dao层
@Repository
public class UserDao {
public List<User> findAll() {
// 模拟数据库查询
return Arrays.asList(new User("Alice", 25), new User("Bob", 30));
}
}
核心注解:
@Component
:声明Bean(通用)@Controller
、@Service
、@Repository
:按层分类的Bean@Autowired
:自动注入依赖示例:手动配置Bean
@Configuration
public class AppConfig {
@Bean
public UserDao userDao() {
return new UserDao();
}
}
示例:日志记录切面
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
public void logAfterReturning(Object result) {
System.out.println("After returning: " + result);
}
}
示例:匹配带有@Loggable
注解的方法
@Pointcut("@annotation(com.example.annotation.Loggable)")
public void loggableMethods() {}
@Around("loggableMethods()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Around before");
Object result = joinPoint.proceed();
System.out.println("Around after");
return result;
}
继承:统一管理依赖版本
<project>
<groupId>com.examplegroupId>
<artifactId>parentartifactId>
<version>1.0.0version>
<packaging>pompackaging>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<version>3.2.0version>
dependency>
dependencies>
dependencyManagement>
project>
<project>
<parent>
<groupId>com.examplegroupId>
<artifactId>parentartifactId>
<version>1.0.0version>
parent>
<artifactId>childartifactId>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
project>
聚合:快速构建多模块项目
<project>
<groupId>com.examplegroupId>
<artifactId>aggregatorartifactId>
<version>1.0.0version>
<packaging>pompackaging>
<modules>
<module>module1module>
<module>module2module>
modules>
project>
settings.xml
<servers>
<server>
<id>nexus-releasesid>
<username>adminusername>
<password>admin123password>
server>
servers>
<mirrors>
<mirror>
<id>nexusid>
<url>http://localhost:8081/repository/maven-public/url>
<mirrorOf>*mirrorOf>
mirror>
mirrors>
mvn deploy -DaltDeploymentRepository=nexus-releases::default::http://localhost:8081/repository/maven-releases/
Spring Boot配置优先级(从高到低):
SPRING_APPLICATION_JSON
环境变量System.getProperties()
)application.properties
/application.yml
示例:配置多例Bean
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public User user() {
return new User();
}
使用@Bean
声明第三方组件:
@Configuration
public class ThirdPartyConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}