1.@Configuration+@Bean编写配置类
此时,第三方类为DataSource;
/** * @Author lucky * @Date 2022/4/1 9:18 * 配置数据库连接池,注入DataSource */ @Configuration public class DruidConfig { @Autowired private DataSourceProperties dataSourceProperties; @Bean public DataSource druidDataSource(){ DruidDataSource druidDataSource=new DruidDataSource(); druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName()); druidDataSource.setUrl(dataSourceProperties.getUrl()); druidDataSource.setUsername(dataSourceProperties.getUsername()); druidDataSource.setPassword(dataSourceProperties.getPassword()); druidDataSource.setInitialSize(dataSourceProperties.getInitialSize()); druidDataSource.setMinIdle(dataSourceProperties.getMinIdle()); druidDataSource.setMaxActive(dataSourceProperties.getMaxActive()); druidDataSource.setMaxWait(dataSourceProperties.getMaxWait()); druidDataSource.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis()); druidDataSource.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis()); druidDataSource.setValidationQuery(dataSourceProperties.getValidationQuery()); druidDataSource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle()); druidDataSource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow()); druidDataSource.setTestOnReturn(dataSourceProperties.isTestOnReturn()); try { druidDataSource.init(); } catch (SQLException e) { e.printStackTrace(); } return druidDataSource; } }
2.测试案例
@RestController @RequestMapping("/hello") @Api public class HelloController { @Autowired DruidConfig druidConfig; @PostMapping("/login") @ApiOperation(value = "你好") public void login(@RequestParam @ApiParam(name="name",value="对话人",required=true) String name){ DataSource dataSource = druidConfig.druidDataSource(); DataSource dataSource2 = druidConfig.druidDataSource(); System.out.println("hello!"+name); } }
通过自动装配,生成的DataSource被spring托管的,单例模式;
标签:name,--,spring,dataSourceProperties,DataSource,Springcloud,druidDataSource,Confi From: https://www.cnblogs.com/luckyplj/p/16851572.html