spring4注解配置datasource方式
Posted danial7777777
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
获得数据库连接池对象
以上是关于spring4注解配置datasource方式的主要内容,如果未能解决你的问题,请参考以下文章
spring boot01,spring完全注解(零配置)编程方式