# spring-boot-learning
**Repository Path**: lizhiyong16/spring-boot-learning
## Basic Information
- **Project Name**: spring-boot-learning
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2023-11-14
- **Last Updated**: 2023-12-04
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# spring-boot-learning
1. 继承 spring-boot-starter-parent
```xml
org.springframework.boot
spring-boot-starter-parent
2.7.17
```
2. 添加依赖 spring-boot-starter
```xml
org.springframework.boot
spring-boot-starter
```
3. 添加依赖 spring-boot-config-processor(可选),目的是去除 application.yml 中的警告
```xml
org.springframework.boot
spring-boot-configuration-processor
true
```
## 1. web
1. 添加依赖 `spring-boot-starter-web`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
## 2. properties
1. 添加依赖 `spring-boot-starter-web`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. 注入 `application.yaml` 配置的属性,属性类添加 `@Configuration` 注解,注入属性有两种方式:`@Value("${application.name}")` 和 `@ConfigurationProperties`
## 3. actuator
1. 添加依赖 `spring-boot-starter-web` 和 `spring-boot-starter-actuator`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. 配置 actuator,暴露 actuator 相关的接口
```yaml
management:
endpoints:
web:
base-path: /actuator
exposure:
# 配置监控暴露的信息(*暴露全部信息)
include: "*"
endpoint:
health:
show-details: always
```
## 4. admin
### admin-server
1. 添加依赖 `spring-boot-starter-web` 和 `spring-boot-admin-starter-server`
```xml
de.codecentric
spring-boot-admin-starter-server
```
2. 主类添加 `@SpringBootApplication` 和 `@EnableAdminServer` 注解,main 调用 `SpringApplication.run` 方法
### admin-client
1. 添加依赖 `spring-boot-starter-web` 和 `spring-boot-admin-starter-client`
```xml
de.codecentric
spring-boot-admin-starter-client
```
2. 配置 client 端信息,注册到 admin-server
```yaml
spring:
application:
name: my-web-9004
boot:
admin:
client:
# admin地址,client注册到admin服务上
url: http://localhost:9003
```
## 5. logback
1. 添加依赖 `spring-boot-starter-web` 和 `spring-boot-starter-logback`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. 配置 logback-spring.xml
```java
// org.springframework.boot.logging.logback.LogbackLoggingSystem.getStandardConfigLocations
@Override
protected String[] getStandardConfigLocations() {
return new String[] { "logback-test.groovy", "logback-test.xml", "logback.groovy", "logback.xml" };
}
```
```xml
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
logs/logback.%d{yyyy-MM-dd}.%i.log
3
100KB
10KB
```
## 6. log-aop
1. 添加依赖 `spring-boot-starter-web` 和 `spring-boot-starter-aop`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. 配置 logback-spring.xml
4. 创建切面类,添加 `@Aspect` 注解,添加切点 `@Pointcut` 注解,添加通知 `@Before` 注解
```java
@Aspect
@Component
public class LogAspect {
@Around("execution(* io.zhiyong.controller.*Controller.*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("before {}", joinPoint.toLongString());
Object result = joinPoint.proceed();
log.info("after {}", joinPoint.toLongString());
return result;
}
}
```
## 7. exception-handler
1. 添加依赖 `spring-boot-starter-web`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. 统一异常处理类,添加 `@ControllerAdvice` 注解,添加 `@ExceptionHandler` 注解
```java
@ControllerAdvice
public class APIExceptionHandler {
@ExceptionHandler(value = APIException.class)
public APIResponse apiExceptionHandler(HttpServletRequest request, APIException e) {
log.error("exceptionHandler", e);
return APIResponse.ofError(e, null);
}
}
```
## 8. template-freemarker
1. 添加依赖 `spring-boot-starter-web` 和 `spring-boot-starter-freemarker`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. controller 返回 ModelAndView
```java
@GetMapping("login")
public ModelAndView login(HttpServletRequest request) {
if (null != request.getSession().getAttribute("user")) {
return new ModelAndView("redirect:/index");
}
return new ModelAndView("login");
}
```
4. 配置 freemarker,ftl 页面放在 templates 目录下,配置属性参考 `FreeMarkerProperties`
```yaml
spring:
freemarker:
suffix: .ftl
template-loader-path: classpath:/templates/
```
## 9. template-thymeleaf
1. 添加依赖 `spring-boot-starter-web` 和 `spring-boot-starter-thymeleaf`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. controller 返回 ModelAndView
4. 配置 thymeleaf,html 页面放在 templates 目录下,配置属性参考 `ThymeleafProperties`
```yaml
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
```
5. thymeleaf 页面需要使用 th:text 等标签,html头部添加 thymeleaf 标识 ``
## 10. template-beetl
1. 添加依赖 `spring-boot-starter-web` 和 `com.ibeetl:beetl-framework-starter`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. controller 返回 ModelAndView
4. 配置 beetl,html 页面放在 templates 目录下,配置属性参考 `BeetlTemplateConfig`
```yaml
beetl:
templatesPath: templates
suffix: btl
```
## 11. template-jfinal
1. 添加依赖 `spring-boot-starter-web` 和 `com.jfinal:enjoy`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. controller 返回 ModelAndView
4. 配置 JFinalViewResolver,html 页面放在 templates 目录下
```java
@Bean(name = "jfinalViewResolver")
public JFinalViewResolver getJFinalViewResolver() {
// 创建用于整合 spring boot 的 ViewResolver 扩展对象
JFinalViewResolver jfr = new JFinalViewResolver();
// 对 spring boot 进行配置
jfr.setSuffix(".html");
jfr.setContentType("text/html;charset=UTF-8");
jfr.setOrder(0);
// 设置在模板中可通过 #(session.value) 访问 session 中的数据
jfr.setSessionInView(true);
// 获取 engine 对象,对 enjoy 模板引擎进行配置,配置方式与前面章节完全一样
Engine engine = JFinalViewResolver.engine;
// 热加载配置能对后续配置产生影响,需要放在最前面
engine.setDevMode(true);
// 使用 ClassPathSourceFactory 从 class path 与 jar 包中加载模板文件
engine.setToClassPathSourceFactory();
// 在使用 ClassPathSourceFactory 时要使用 setBaseTemplatePath
engine.setBaseTemplatePath("/templates/");
return jfr;
}
```
12. jdbctemplate
1. 添加依赖 `spring-boot-starter-jdbc` 和 `mysql:mysql-connector-java`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. 创建 Dao 层父类 BaseDao, 实现增删改查操作
```java
public class BaseDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public T findById(ID id) {
String sql = String.format("select * from %s where id = ?", getTableName());
return jdbcTemplate.queryForObject(sql, BeanPropertyRowMapper.newInstance(entityClass), id);
}
public List findAll() {
String sql = String.format("select * from %s", getTableName());
return jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(entityClass));
}
public boolean deleteById(ID id) {
String sql = String.format("delete from %s where id =?", getTableName());
return jdbcTemplate.update(sql, id) > 0;
}
}
```
4. 配置数据源和数据库连接池,配置属性参考 `DataSourceProperties`、 `SqlInitializationProperties` 和 `HikariConfigMXBean`
```yaml
spring:
sql:
init:
mode: always
continue-on-error: true
schema-locations:
- classpath:db/schema/user.sql
data-locations:
- classpath:db/data/user.sql
datasource:
url: jdbc:mysql://192.168.10.6:3306/spring-boot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 'Mysql@8080'
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 5
maximum-pool-size: 20
auto-commit: true
idle-timeout: 30000
pool-name: SpringBootHikariCP
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1
```
13. jpa
1. 添加依赖 `spring-boot-starter-data-jpa` 和 `mysql:mysql-connector-java`
2. 主类添加 `@SpringBootApplication` 注解,main 调用 `SpringApplication.run` 方法
3. 添加 `JpaConfiguration` 配置类
```java
@Configuration
@EnableJpaRepositories(basePackages = {"io.zhiyong.repository"})
public class JpaConfiguration {
// @Bean
// @ConfigurationProperties(prefix = "spring.datasource")
// public DataSource dataSource() {
// return DataSourceBuilder.create().build();
// }
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan("io.zhiyong.entity");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.MYSQL);
vendorAdapter.setGenerateDdl(true);
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
return entityManagerFactoryBean;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
```
14. mybatis
1. 添加依赖 `org.mybatis.spring.boot:mybatis-spring-boot-starter` 和 `mysql:mysql-connector-java`
2. 主类添加 `@SpringBootApplication` 和 `MapperScan` 注解
3. 配置数据源和mybatis,配置属性参考 `DataSourceProperties`、 `SqlInitializationProperties` 、 `HikariConfigMXBean`、 `MybatisProperties`
```yaml
spring:
datasource:
url: jdbc:mysql://192.168.10.6:3306/spring-boot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 'Mysql@8080'
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: io.zhiyong.entity
```
15. mybatis-mapper-pagehelper
1. 添加依赖 `com.github.pagehelper:pagehelper-spring-boot-starter` 和 `tk.mybatis:mapper-spring-boot-starter`
2. 主类添加 `@SpringBootApplication` 和 `MapperScan` 注解
3. 配置数据源和mybatis,配置属性参考 `DataSourceProperties`、 `SqlInitializationProperties` 、 `HikariConfigMXBean`、 `MybatisProperties`
```yaml
spring:
datasource:
url: jdbc:mysql://192.168.10.6:3306/spring-boot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 'Mysql@8080'
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: io.zhiyong.entity
```