关于springboot starter
我们在使用springboot时, 会使用到各种starter, 这些starter提高了我们开发效率, 至于starter是什么? 它是怎么启动的? 在这里我们要对其做一个详细的了解
启动器
springboot的启动器, springboot在启动时会扫描所有包下面的
META_INF/spring.factories
文件, 将该文件中所有启动类全部加载到spring容器中, 我们只需要在application.yml
中设置对应的启动配置文件即可
实现一个mysql启动类
1. 创建maven项目, 添加下面的依赖包
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2. 编写配置类和启动类
# 配置类
@Data
@ConfigurationProperties(prefix = "inus.mysql")
//@Component
public class MysqlProperites {
private String driverClassName;
private String url;
private String username;
private String password;
}
# 启动类
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(MysqlProperites.class)
//@ComponentScan("com.inus.nacos")
public class MysqlStarterConfiguration {
@Autowired
private MysqlProperites properites;
@Bean
public Connection connection() throws ClassNotFoundException, SQLException {
Class.forName(properites.getDriverClassName());
Connection connection = DriverManager.getConnection(properites.getUrl(), properites.getUsername(),
properites.getPassword());
return connection;
}
}
3. 启动类添加自启动
# 新建META-INF/spring.factories
# 添加启动配置类
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.inus.nacos.configuration.MysqlStarterConfiguration
至此mysql启动类已经编写完成, 下面我们写个测试程序测试该启动类
测试mysql启动类
1. yml配置
inus:
mysql:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/xbb_oa?useUnicode=true&characterEncoding=utf8&serverTimezone=CTT
username: root
password: root
2. 注入启动类中的connection
@Autowired
private Connection connection;
@RequestMapping("user")
public User user(String id) throws SQLException {
PreparedStatement statement = connection.prepareStatement("select * from oa_user where id=?");
statement.setString(1, id);
User user = null;
ResultSet rs = statement.executeQuery();
while (rs.next()) {
user = new User()//
.setName(rs.getString("name"))//
.setAccount(rs.getString("account"));
break;
}
return user;
}