栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

模仿springboot自动配置datasource

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

模仿springboot自动配置datasource

1、创建一个自己的spring-boot-starter(叫啥都行),结构如下:

2、导入依赖

    需要依赖spring-boot-starter。因为需要用到springboot的注解。



    
        sprintboot02
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    mydruid-spring-boot-starter
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.projectlombok
            lombok
            1.18.24
        
    


3、准备需要注入的bean
@Data
public class DataSource {
    private String driver;
    private String url;
    private String username;
    private String password;
}
4、准备配置类
@Configuration
public class AppConfig {
    @Bean
    @ConditionalOnMissingBean
    @ConfigurationProperties(prefix = "config.datasource")
    public DataSource getDataSource(){
        return new DataSource();
    }
}
@Conditional注解的所有类型:


5、创建META-IFO文件夹,开启自动扫描

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xycf.common.config.AppConfig

6、打包

7、创建一个web项目,将刚刚打包的项目导入依赖



    
        sprintboot02
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    springboot02-child
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
        
        
            org.example
            mydruid-spring-boot-starter
            1.0-SNAPSHOT
        
    


8、配置yml文件

@ConfigurationProperties(prefix=“xxx”)会读取文件中以xxx为前缀的所有值并注入到实体bean中

config:
  datasource:
    driver: 111
    url: 222
    username: 333
    password: 444

9、编写测试类

package com.xycf.springboot;

import com.xycf.common.entity.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@SpringBootTest(classes = SpringbootApplication.class)
@RunWith(SpringRunner.class)
public class SpringbootApplicationTest {
    @Autowired
    private DataSource dataSource;
    @Test
    public void test(){
        System.out.println(dataSource);
    }
}

结果如下

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936075.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号