SpringBoot启动流程-new SpringApplication

new SpringApplication()主要过程

根据spring.factories配置文件,找到配置的应用上下文类(#Application Context Initializers)和监听器类(#Application Listeners),并根据反射机制创建相应对象,最后推断出包含main方法的主类。

1.推断应用web类型

默认是servlet

 

2.设置ApplicationContextInitializer和ApplicationListener

总结:通过读取spring.factories文件获取全部类全限定名--->根据Initializer和ApplicationListener获取对应类全限定名--->根据类全限定名使用反射方法创建对应的对象--->将对象赋值给SpringApplication对象的initializers属性。

this.initializers.addAll(initializers);

 

6个ApplicationContextInitializer

//核心方法
setInitializers((Collection)getSpringFactoriesInstances(ApplicationContextInitializer.class));
Class.forName(url);
class.getConstructor(class...).newInstance(param..) 

(1)获取类全限定名

首先读取所有jar包中的spring.factories文件中的类全限定名,然后利用key、value存储到map中。再使用key = org.springframework.context.ApplicationContextInitializer,从map中获取对应的value值,获取到6个Initializer。

[org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer, 
org.springframework.boot.context.ContextIdApplicationContextInitializer, 
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,
 org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer, 
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer, 
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener]

(2)反射方式创建对象

forName(elementClassName, classLoader);//利用classloader和类全限定名获取class对象
instanceClass.getDeclaredConstructor(parameterTypes);//获取类的构造器
ctor.newInstance(args);//利用构造器创建对象
 

13个ApplicationListener

设置思路和上述Initializer一样。

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.listeners.addAll(listeners);//将获取到的listener对象设置到SpringApplication对象的属性中
[org.springframework.cloud.bootstrap.BootstrapApplicationListener, 
org.springframework.cloud.bootstrap.LoggingSystemShutdownListener, 
org.springframework.cloud.context.restart.RestartListener, 
org.springframework.boot.ClearCachesApplicationListener, 
org.springframework.boot.builder.ParentContextCloserApplicationListener, 
org.springframework.boot.context.FileEncodingApplicationListener, 
org.springframework.boot.context.config.AnsiOutputApplicationListener, 
org.springframework.boot.context.config.ConfigFileApplicationListener, 
org.springframework.boot.context.config.DelegatingApplicationListener, 
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener, 
org.springframework.boot.context.logging.LoggingApplicationListener, 
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener, 
org.springframework.boot.autoconfigure.BackgroundPreinitializer]

3.推断出当前主类

总结:通过RuntimeException().getStackTrace()获取运行时堆栈信息,遍历堆栈元素方法名是否为“main”,利用Class.forName(className)推断出运行主类。

//根据栈中的方法名是否包含main,推断当前main方法所在的类
this.mainApplicationClass = deduceMainApplicationClass();

//deduceMainApplicationClass()核心代码
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					return Class.forName(stackTraceElement.getClassName());
				}
			}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个非常流行的 Java Web 框架,而 MyBatis-Plus 是一个优秀的 ORM 框架,它可以帮助我们更加方便地操作数据库。本篇文章将介绍如何在 Spring Boot 中整合 MyBatis-Plus 3.1。 ## 1. 准备工作 在开始整合之前,我们需要准备好以下环境: - JDK 8+ - Maven 3.2+ - IDE(例如 IntelliJ IDEA 或 Eclipse) ## 2. 创建 Spring Boot 项目 首先,我们需要创建一个 Spring Boot 项目。可以使用 Spring Initializr 来快速创建一个项目。在创建项目的过程中,我们需要选择以下的依赖: - Spring Web - MyBatis-Plus 如果你使用的是 IntelliJ IDEA,可以使用以下方式创建项目: 1. 打开 IntelliJ IDEA,选择 "Create New Project"。 2. 在弹出的对话框中选择 "Spring Initializr"。 3. 配置项目的基本信息,例如 Group、Artifact、Name 等。 4. 在 "Dependencies" 中选择 "Spring Web" 和 "MyBatis-Plus"。 5. 点击 "Next",确认配置信息。 6. 点击 "Finish",完成项目的创建。 如果你使用的是 Eclipse,可以参考以下的步骤: 1. 打开 Eclipse,选择 "File" -> "New" -> "Other"。 2. 在弹出的对话框中选择 "Spring Starter Project"。 3. 配置项目的基本信息,例如 Group、Artifact、Name 等。 4. 在 "Dependencies" 中选择 "Spring Web" 和 "MyBatis-Plus"。 5. 点击 "Finish",完成项目的创建。 ## 3. 配置 MyBatis-Plus 完成项目的创建后,我们需要进行一些配置,以便让 Spring Boot 和 MyBatis-Plus 正常工作。 ### 3.1 配置数据源 首先,我们需要配置数据源。在 Spring Boot 中,我们可以使用以下方式配置数据源: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 这里我们使用的是 MySQL 数据库,你可以根据自己的实际情况进行修改。 2. 在启动类中添加 @EnableTransactionManagement 注解,开启事务管理: ```java @SpringBootApplication @EnableTransactionManagement public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` ### 3.2 配置 MyBatis-Plus 接下来,我们需要配置 MyBatis-Plus。在 Spring Boot 中,我们可以使用以下方式配置 MyBatis-Plus: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml mybatis-plus: mapper-locations: classpath*:mapper/*.xml type-aliases-package: com.example.demo.entity ``` 这里的 mapper-locations 表示 Mapper 文件的位置,type-aliases-package 表示实体类的包路径。 2. 在启动类中添加 @MapperScan 注解,指定 Mapper 文件的包路径: ```java @SpringBootApplication @EnableTransactionManagement @MapperScan("com.example.demo.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` ### 3.3 配置分页插件 MyBatis-Plus 内置了一个分页插件,可以帮助我们更加方便地进行分页查询。 在 Spring Boot 中,我们可以使用以下方式配置分页插件: 1. 在 application.properties 或 application.yml 中添加以下配置: ```yaml mybatis-plus: configuration: # 分页插件 page-helper: helper-dialect: mysql reasonable: true support-methods-arguments: true params: count=countSql ``` 这里的 helper-dialect 表示数据库类型,reasonable 表示是否启用合理化查询,support-methods-arguments 表示支持多参数查询,params 表示传递给 Mapper 的参数名。 2. 在 Mapper 接口中添加 Page 参数,如下所示: ```java public interface UserMapper extends BaseMapper<User> { List<User> selectUserList(Page<User> page); } ``` ### 3.4 配置自动填充插件 MyBatis-Plus 还内置了一个自动填充插件,可以帮助我们更加方便地进行数据填充。 在 Spring Boot 中,我们可以使用以下方式配置自动填充插件: 1. 在实体类中添加 @TableField 注解,并指定填充策略: ```java @Data public class User { private Long id; private String name; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; } ``` 这里的 fill 表示填充策略,INSERT 表示插入时填充,UPDATE 表示更新时填充。 2. 在 Mapper 接口中添加 @Insert 注解,并指定插入方式: ```java public interface UserMapper extends BaseMapper<User> { @Insert("insert into user(name,create_time,update_time) values(#{name},#{createTime},#{updateTime})") int insertUser(User user); } ``` 这里的 @Insert 注解表示插入数据,#{} 中的属性名与实体类中的属性名一致。 ## 4. 使用 MyBatis-Plus 完成配置后,我们就可以使用 MyBatis-Plus 进行数据库操作了。下面我们来看一些使用示例。 ### 4.1 基本操作 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User selectById(Long id) { return userMapper.selectById(id); } public List<User> selectList() { return userMapper.selectList(null); } public int insert(User user) { return userMapper.insert(user); } public int updateById(User user) { return userMapper.updateById(user); } public int deleteById(Long id) { return userMapper.deleteById(id); } } ``` 这里的 selectById、selectList、insert、updateById、deleteById 分别表示根据 id 查询、查询列表、插入、更新和删除。 ### 4.2 分页查询 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public List<User> selectUserList(int pageNum, int pageSize) { Page<User> page = new Page<>(pageNum, pageSize); return userMapper.selectUserList(page); } } ``` 这里的 selectUserList 表示分页查询,pageNum 表示页码,pageSize 表示每页大小。Page<User> 表示分页对象。 ### 4.3 自动填充 ```java @RestController public class UserController { @Autowired private UserService userService; @PostMapping("/user") public int insert(User user) { return userService.insert(user); } } ``` 这里的 insert 表示插入数据,当插入数据时,createTime 和 updateTime 会自动填充。 ## 5. 总结 本篇文章介绍了如何在 Spring Boot 中整合 MyBatis-Plus 3.1。首先,我们需要创建一个 Spring Boot 项目,并添加相应的依赖。然后,我们需要进行一些配置,包括数据源、MyBatis-Plus、分页插件和自动填充插件。最后,我们使用 MyBatis-Plus 进行数据库操作。 MyBatis-Plus 是一个非常优秀的 ORM 框架,它可以帮助我们更加方便地操作数据库。如果你想提高自己的开发效率,不妨尝试一下 MyBatis-Plus。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值