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

    获得数据库连接池对象

  • 相关阅读:
    大象起舞:用PostgreSQL解海盗分金问题
    python 导入模块
    python socket 发送ESB报文
    python socket超时
    ISCC2018部分WriteUp
    查看SQL执行计划的方法及优劣
    jquery遮罩层
    IE9 JS不执行,打开F12就没问题了
    BigDecimal 01
    BigDecimal 01
  • 原文地址:https://www.cnblogs.com/Danial7777777/p/10766020.html
Copyright © 2011-2022 走看看