码迷,mamicode.com
首页 > 编程语言 > 详细

spring4注解配置datasource方式

时间:2019-04-25 09:12:16      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:mysq   inf   ring   system   配置   text   sys   ignore   ice   

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

技术图片

获得数据库连接池对象

技术图片

 

spring4注解配置datasource方式

标签:mysq   inf   ring   system   配置   text   sys   ignore   ice   

原文地址:https://www.cnblogs.com/Danial7777777/p/10766020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!