Springboot+Druid——MySQL 古城微笑少年丶 2022-02-20 03:31 110阅读 0赞 1.[新建一个Springboot Project][Springboot Project] 2.导入Druid所需的依赖(不同的连接池只需要导入不同的依赖即可) 导入MySQL数据库依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> 3.新建一个Class类,包路径随意 ![新建一个类][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MDQyOTAzMA_size_16_color_FFFFFF_t_70] 4 编写该类 @1. 将该类上再上@Configuration注解,定义所用到的变量,使用@Value标签进行参数注入 @2.编写一个方法返回类型为DataSource,并加上注解@Bean,@Primary @Configuration public class DruidDatasourceConfig { @Value("${spring.datasourse.driver-class-name}") private String driverClassName; @Value("${spring.datasourse.url}") private String url; @Value("${spring.datasourse.userName}") private String userName; @Value("${spring.datasourse.password}")//使用Bean方式进行参数注入 private String password; @Bean//加载Bean @Primary//优先注入 public DataSource dataSource() { DruidDataSource dataSource=new DruidDataSource();//使用不同的连接池此处需要更换为对应的连接池实现类 dataSource.setDriverClassName(driverClassName);//此处仅为演示故没有注入太多的参数 dataSource.setUrl(url); dataSource.setUsername(userName); dataSource.setPassword(password); return dataSource; } } 5.检查此时DataSource类型 在启动类中添加DataSource成员变量并使用@@Autowired注解进行注入 在启动类中实现CommandLineRunner接口,并重写run方法打印DataSource类名 @SpringBootApplication public class MainApp implements CommandLineRunner{ @Autowired DataSource dataSource; public static void main(String[] args) { SpringApplication.run(MainApp.class, args); } public void run(String... args) throws Exception { System.out.println(dataSource.getClass().getName()); } } 6.在启动时可以发现控制台打印的类名为com.alibaba.druid.pool.DruidDataSource ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MDQyOTAzMA_size_16_color_FFFFFF_t_70 1] 7. [Springboot Project]: https://blog.csdn.net/weixin_40429030/article/details/89233334 [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MDQyOTAzMA_size_16_color_FFFFFF_t_70]: /images/20220220/c9810d715cc14a86be9526d90a720e3f.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MDQyOTAzMA_size_16_color_FFFFFF_t_70 1]: /images/20220220/9862185662b441d597c5d31e92828746.png
还没有评论,来说两句吧...