zoukankan      html  css  js  c++  java
  • spring4注解配置datasource方式

    package com.boot.config;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    import javax.sql.DataSource;
    
    public class Main {
    
        public static void main(String[] args) {
    
            AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
            DataSource boneCPDataSource = (DataSource) context.getBean("boneCPDataSource");
            //UserService userService = context.getBean(UserService.class);
            //List<User> users = userService.queryUserList();
            //System.out.println(users);
            context.close();
        }
    
    }
    package com.boot.config;
    
    import com.jolbox.bonecp.BoneCPDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    //配置注解
    @Configuration
    //扫描
    @ComponentScan(basePackages = "com.boot.config")
    @PropertySource(value = {"classpath:jdbc.properties"},ignoreResourceNotFound=true)
    public class SpringConfig {
    
        @Value("${jdbc.driverClassName}")
        private String driverClassName;
    
        @Value("${jdbc.url}")
        private String url;
    
        @Value("${jdbc.username}")
        private String username;
    
        @Value("${jdbc.password}")
        private String password;
    
        //@Bean  //相当于xml配置文件的bean注解   初始化userDao
        //public UserDAO getUserDao(){
        //    return new UserDAO();//返回对象
        //}
    
        //bean默认id为方法名
        @Bean(destroyMethod="close")
        public BoneCPDataSource boneCPDataSource(){
            //配置数据库连接池对象
            BoneCPDataSource boneCPDataSource=new BoneCPDataSource();
            boneCPDataSource.setDriverClass(driverClassName);
            boneCPDataSource.setUsername(username);
            boneCPDataSource.setPassword(password);
            boneCPDataSource.setJdbcUrl(url);
            return boneCPDataSource;
        }
    
    
    }
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis
    jdbc.username=root
    jdbc.password=123456

    获得数据库连接池对象

  • 相关阅读:
    MySQL锁之三:MySQL的共享锁与排它锁编码演示
    服务链路追踪(Spring Cloud Sleuth)
    服务网关zuul之四:zuul网关配置
    hdu 1505 City Game (hdu1506加强版)
    PHP设计模式——訪问者模式
    极客互联网电视不是噱头,用户体验成创维G7200核心竞争力
    深入理解JavaScript系列(23):JavaScript与DOM(上)——也适用于新手
    使用php分页类实现简单分类
    管理之路(四)
    poj 2485 Highways (最小生成树)
  • 原文地址:https://www.cnblogs.com/Danial7777777/p/10766020.html
Copyright © 2011-2022 走看看