SPRING IN ACTION 第4版笔记-第十章Hitting the database with spring and jdbc-003-四种方式获取DataSource
一、概述
1.Spring offers several options for configuring data-source beans in your Spring application, including these:
 Data sources that are defined by a JDBC driver
 Data sources that are looked up by  JNDI
 Data sources that pool connections
2.
二、四种方式获取DataSource
1. Using JNDI data sources
(1)java方式
@Bean
public JndiObjectFactoryBean dataSource() {
JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean();
jndiObjectFB.setJndiName("jdbc/SpittrDS");
jndiObjectFB.setResourceRef(true);
jndiObjectFB.setProxyInterface(javax.sql.DataSource.class);
return jndiObjectFB;
}
(2)xml方式
<jee:jndi-lookup id="dataSource" jndi-name="/jdbc/SpitterDS" resource-ref="true" />
The jndi-name attribute is used to specify the name of the resource in JNDI . If only the jndi-name property is set, then the data source will be looked up using the name given as is. But if the application is running in a Java application server, you’ll want to set the resource-ref property to true so that the value given in jndi-name will be prepended with java:comp/env/
2.Using a pooled data source
(1)java方式
@Bean
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:tcp://localhost/~/spitter");
ds.setUsername("sa");
ds.setPassword("");
ds.setInitialSize(5);
ds.setMaxActive(10);
return ds;
}
(2)xml方式
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="org.h2.Driver"
p:url="jdbc:h2:tcp://localhost/~/spitter"
p:username="sa"
p:password=""
p:initialSize="5"
p:maxActive="10" />

3.Using JDBC driver-based data sources(不支持连接池)
有3种选择:
 DriverManagerDataSource —Returns a new connection every time a connection is requested. Unlike DBCP ’s BasicDataSource , the connections provided by DriverManagerDataSource aren’t pooled.
 SimpleDriverDataSource —Works much the same as  DriverManagerDataSource except that it works with the  JDBC driver directly to overcome class loading issues that may arise in certain environments, such as in an  OSG i container.
 SingleConnectionDataSource —Returns the same connection every time a connection is requested. Although  SingleConnectionDataSource isn’t exactly a pooled data source, you can think of it as a data source with a pool of exactly
one connection.
(1)java方式
@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:tcp://localhost/~/spitter");
ds.setUsername("sa");
ds.setPassword("");
return ds;
}
(2)xml方式
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.h2.Driver"
p:url="jdbc:h2:tcp://localhost/~/spitter"
p:username="sa"
p:password="" />
The only significant difference with these data-source beans as compared to the pooling data-source beans is that because they don’t provide a connection pool, there are no pool configuration properties to set.
4.Using an embedded data source(适合测试用)
Although it’s not very useful in production settings, an embedded database is a perfect choice for development and testing purposes. That’s because it allows you to populate your database with test data that’s reset every time you restart your application or run your tests.
(1)java方式
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql")
.addScript("classpath:test-data.sql")
.build();
}
(2)xml方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
...
<jdbc:embedded- database id="dataSource" type="H2">
<jdbc:script location="com/habuma/spitter/db/jdbc/schema.sql" />
<jdbc:script location="com/habuma/spitter/db/jdbc/test-data.sql" />
</jdbc:embedded-database> ...
</beans>
5. Using profiles to select a data source
生产、测试等不同环境要用不同的数据源,可用profile实现自动切换
(1)java方式
package com.habuma.spittr.config;
import org.apache.commons.dbcp.BasicDataSource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.jndi.JndiObjectFactoryBean;
@Configuration
public class DataSourceConfiguration {
@Profile("development")
@Bean
public DataSource embeddedDataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql")
.addScript("classpath:test-data.sql")
.build();
}
@Profile("qa")
@Bean
public DataSource Data() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:tcp://localhost/~/spitter");
ds.setUsername("sa");
ds.setPassword("");
ds.setInitialSize(5);
ds.setMaxActive(10);
return ds;
}
@Profile("production")
@Bean
public DataSource dataSource() {
JndiObjectFactoryBean jndiObjectFactoryBean
= new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
jndiObjectFactoryBean.setResourceRef(true);
jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
return (DataSource) jndiObjectFactoryBean.getObject();
}
}
(2)xml方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<beans profile="development">
<jdbc:embedded- database id="dataSource" type="H2">
<jdbc:script location="com/habuma/spitter/db/jdbc/schema.sql" />
<jdbc:script location="com/habuma/spitter/db/jdbc/test-data.sql" />
</jdbc:embedded- database>
</beans>
<beans profile="qa">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="org.h2.Driver"
p:url="jdbc:h2:tcp://localhost/~/spitter"
p:username="sa" p:password=""
p:initialSize="5"
p:maxActive="10" />
</beans>
<beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="/jdbc/SpitterDS" resource-ref="true" />
</beans>
</beans>
SPRING IN ACTION 第4版笔记-第十章Hitting the database with spring and jdbc-003-四种方式获取DataSource的更多相关文章
- SPRING IN ACTION 第4版笔记-第十章Hitting the database with spring and jdbc-001-Spring对原始JDBC的封装
		
1.spring扩展的jdbc异常 2.Template的运行机制 Spring separates the fixed and variable parts of the data-access p ...
 - SPRING IN ACTION 第4版笔记-第十章Hitting the database with spring and jdbc-004-使用NamedParameterJdbcTemplate
		
为了使查询数据库时,可以使用命名参数,则要用NamedParameterJdbcTemplate 1.Java文件配置 @Bean public NamedParameterJdbcTemplate ...
 - SPRING IN ACTION 第4版笔记-第十章Hitting the database with spring and jdbc-002-本章的源代码
		
0.结构 一.JDBC层 1. package spittr.db; import java.util.List; import spittr.domain.Spitter; /** * Reposi ...
 - SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-003-Spring对AOP支持情况的介绍
		
一. 不同的Aop框架在支持aspect何时.如何织入到目标中是不一样的.如AspectJ和Jboss支持在构造函数和field被修改时织入,但spring不支持,spring只支持一般method的 ...
 - SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice
		
No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...
 - SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-002- Spring的JSP标签之form标签(<sf:input><sf:errors><sf:form>)
		
一. Spring offers two JSP tag libraries to help define the view of your Spring MVC web views. One tag ...
 - SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error
		
一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...
 - SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-006-给bean运行时注入值(Environment,Property文件)
		
一. 直观的给bean注入值如下: @Bean public CompactDisc sgtPeppers() { return new BlankDisc( "Sgt. Pepper's ...
 - SPRING IN ACTION 第4版笔记-第三章Advancing wiring-001-DataSource在应用和开发环境之间切换 profile
		
一. DataSource在应用和开发环境的产生方式不同,可以用srping 的profile管理 Spring’s solution for environment-specific beans i ...
 
随机推荐
- mozilla css developer center
			
https://developer.mozilla.org/en-US/docs/Web/CSS
 - 团队开发——Alpha版总结会议
			
本组目前存在的问题: 1.在选题的时候,题目选的比较有难度,造成后期工作量较大,实现有难度(未能正确估计项目的难度). 2.最初规划时,设计的功能较多,但是技术水平达不到,导致目前完成功能较少. 3. ...
 - Spring集成hibernate错误
			
八月 25, 2016 7:55:31 下午 org.apache.tomcat.util.digester.SetPropertiesRule begin警告: [SetPropertiesRule ...
 - 学习Linux第三天
			
1.常用的命令: reset 清屏 leave +hhmm 建立离开提醒 sudo apt-get yum 安装yum程序 sudo su 切换root身份 see test.c 可以直接查看文件,神 ...
 - bzoj 3171 费用流
			
每个格拆成两个点,出点连能到的点的入点,如果是箭头指向 方向费用就是0,要不就是1,源点连所有出点,所有入点连 汇点,然后费用流 /********************************** ...
 - map初始化定时器
			
init_timer(); //各种定时器的初始化 void Map::init_timer() { //auto tf = GetPlug(TimerFactory); auto tf = m_sp ...
 - .NET设计模式(17):命令模式(Command Pattern)(转)
			
概述 在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”.但在某些场合,比如要对行为进行“记录.撤销/重做.事务”等处理,这种无法抵御变化的紧耦合是不合适的.在这种情况下,如何将“行为 ...
 - Guid和Int还有Double、Date的ToString方法的常见格式
			
Guid的常见格式: 1.Guid.NewGuid().ToString("N") 结果为: 38bddf48f43c48588e0d78761eaa1ce6 2.Gu ...
 - sublime text3使用心得及个人配置 sublime常用快捷键大全
			
下载好后:1.安装package controlimport urllib.request,os; pf = 'Package Control.sublime-package'; ipp = subl ...
 - 利用URLRewriter.dll 实现ASP.NET实现伪静态
			
大家一定经常在网络上看到很多网站的地址后缀都是用XX.HTML或者XX.ASPX等类似静态文件的标示来操作的吧,那么大家有怀疑过他真的是一个一个的静态生成的文件么,静态文件的生成的优缺有好有坏,对于访 ...