SpringBoot - starter mysql dome

SpringBoot starter

1. 使用maven创建两个项目

enable-common 为了测试 mysql-starter
SpringBoot - starter mysql dome_第1张图片

2. mysql-starter 项目添加pom.xml内容
 	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.48</version>
    </dependency>
3.mysql-starter 配置mysql连接的属性
// 读取配置文件中前缀为 mysql的内容
@ConfigurationProperties(prefix = "mysql")
public class MysqlProperties {
	// 以下所有属性全部为默认值
    private String url = "jdbc:mysql://localhost:3306/test";
    private String user = "root";
    private String password = "root";
    private String driverName = "com.mysql.jdbc.Driver";

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverName() {
        return driverName;
    }

    public void setDriverName(String driverName) {
        this.driverName = driverName;
    }
}
4. mysql-starter 创建生成mysql连接 Connection 的配置类
// 这个配置类也需要被注入到spring上下文中
@Configuration
// 因为MysqlProperties类没有自动注入, 所以需要在配置类中使用,就必须使用该注解注入
@EnableConfigurationProperties(MysqlProperties.class)
public class MysqlConfigure {

    @Bean(name = "mysqlConnection")
    // lombok 提供的异常捕获注解
    @lombok.SneakyThrows
    public java.sql.Connection getConnection(MysqlProperties properties){
	    // 加载驱动
        Class.forName(properties.getDriverName());
        // 建立链接
        return DriverManager.getConnection(properties.getUrl(),
                properties.getUser(), properties.getPassword());
    }
}
5. mysql-starterresources目录下创建 META-INF/spring.factories文件
###  注意, 这里前缀是固定的,后缀必须配置自己写的配置类,而不是属性类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.config.MysqlConfigure
6. 配置enable-common项目pom.xml 文件
<!-- 这里引入自己写的starter -->
<!-- 这个项目中不需要再次引入spring-boot-starter , mysql-starter已经包含了-->
<dependency>
  <groupId>org.example</groupId>
  <artifactId>mysql-starter</artifactId>
  <version>1.0-SNAPSHOT</version>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
</dependency>
7. enable-common配置启动类
@SpringBootApplication
public class CommonAutoConfigureApplication {
    public static void main(String[] args) {
       SpringApplication.run(CommonAutoConfigureApplication.class, args);
    }
}
8. enable-common 使用Junit 测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CommonAutoConfigureApplication.class)
public class MySQLTest {

    @Resource(name = "mysqlConnection")
    private Connection connection;



    @Test
    @SneakyThrows
    public void testMyStarter(){
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("select * from tb_user");
        while (rs.next()) {
            // 通过字段检索
            String id = rs.getString("id");
            String name = rs.getString("mobile");
            String password = rs.getString("email");
            System.out.print(" id:" + id);
            System.out.print(" 电话:" + name);
            System.out.print(" 邮箱:" + password + "\n");
        }
        rs.close();
        statement.close();
        connection.close();
        //id:1 电话:123456 邮箱:[email protected]
		//id:2 电话:456789 邮箱:[email protected]
    }
}
9. spring.factories中前缀去哪儿找
  • 进入注解 @SpringBootApplication内部找到 @EnableAutoConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration  // ****找到该注解***
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
  • @EnableAutoConfiguration复制该注解的全路径即可
10. resource/META-INF/spring.factories 源码中能找到吗
  • 重复第九步, 进入@EnableAutoConfiguration注解中找到@Import(AutoConfigurationImportSelector.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)  // ***这里***
public @interface EnableAutoConfiguration {
  • 进入AutoConfigurationImportSelector.class类中 177
// 找到该方法 
//org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getCandidateConfigurations()
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}
11. 总结

(1). 写starter需要依赖spring项目的自动注入和IOC容器.
(2). 在写spring.factories时候一定要放到starter项目中resource/META-INF目录下
(3). 如果需要修改 mysql 的连接属性, 直接在enable-commonapplication.yml添加 以mysql为前缀的内容即可

mysql:
  driverName: com.mysql.cj.jdbc.Driver
  url: jdbc:mysql://localhost:3306/cloud_user?useSSL=false
  user: root
  password: root

(4). 代码地址: https://github.com/Zyred9/boot-starters

你可能感兴趣的:(springboot,starter,spring,boot)