關于springboot starter
我們在使用springboot時, 會使用到各種starter, 這些starter提高了我們開發(fā)效率, 至于starter是什么? 它是怎么啟動的? 在這里我們要對其做一個詳細的了解
啟動器
springboot的啟動器, springboot在啟動時會掃描所有包下面的
META_INF/spring.factories
文件, 將該文件中所有啟動類全部加載到spring容器中, 我們只需要在application.yml
中設置對應的啟動配置文件即可
實現(xiàn)一個mysql啟動類
1. 創(chuàng)建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啟動類已經(jīng)編寫完成, 下面我們寫個測試程序測試該啟動類
測試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;
}