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

获得数据库连接池对象

猜你喜欢

转载自www.cnblogs.com/Danial7777777/p/10766020.html