spring-boot自定义启动器的配置类配置DataSource

springboot项目中使用注解@Autowired自动装配DataSource:

@RestController
public class HelloController {

     @Autowired
    DataSource dataSource;

    @RequestMapping("/hello")
    public String hello() {
        //System.out.println(dataSourceProperties2);
        System.out.println(dataSource.getClass());
        return "hello springboot!!";
    }
}

在启动器所在Module的自定义配置类中使用@Bean注解,创建数据源对象并交给IOC容器管理:

@SpringBootConfiguration //自定义配置类作用相当于: spring.xml
public class DataSourceAutoConfiguration {
     //@Autowired
      @Resource
     DataSourceProperties dataSourceProperties;
     //配置druid数据源
    /*
    *  <bean id="datasource" class="DruidDataSource">
          <property name="username" value="root">
    *      .....
    * */
    @Bean //创建bean对象并在ioc容器中管理
    @ConditionalOnProperty(name ="spring.jdbc.datasource.type" ,havingValue ="druid" )
    public DataSource druidDataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setUsername(dataSourceProperties.getUserName());
        druidDataSource.setPassword(dataSourceProperties.getPassword());
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        return  druidDataSource;
    }

在控制器中,@Autowired注解按type装配DataSource,DataSource是接口,所有实际提供给控制器Controller的是Druid数据源。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值