Java Spring詳解如何配置數(shù)據(jù)源注解開(kāi)發(fā)以及整合Junit
Spring數(shù)據(jù)源的配置
數(shù)據(jù)源(連接池)的作用
數(shù)據(jù)源(連接池)是提高程序性能如出現(xiàn)的
事先實(shí)例化數(shù)據(jù)源,初始化部分連接資源
使用連接資源時(shí)從數(shù)據(jù)源中獲取
使用完畢后將連接資源歸還給數(shù)據(jù)源
常見(jiàn)的數(shù)據(jù)源(連接池):DBCP、C3PO、BoneCP、Druid等
數(shù)據(jù)源的開(kāi)發(fā)步驟
1、導(dǎo)入數(shù)據(jù)源的坐標(biāo)和數(shù)據(jù)庫(kù)驅(qū)動(dòng)坐標(biāo)
2、創(chuàng)建數(shù)據(jù)源對(duì)象
3、設(shè)置數(shù)據(jù)源的基本連接數(shù)據(jù)
4、使用數(shù)據(jù)源獲取連接資源和歸還連接資源
手動(dòng)創(chuàng)建數(shù)據(jù)源
1、導(dǎo)入c3p0和druid坐標(biāo),mysql數(shù)據(jù)庫(kù)驅(qū)動(dòng)坐標(biāo)
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
2、創(chuàng)建C3P0連接池
Test
public void testC3P0 ( ) throws Exception {
//創(chuàng)建數(shù)據(jù)源
ComboPooledDataSource dataSource = new ComboPooledDataSource () ;
//設(shè)置數(shù)據(jù)庫(kù)連接參數(shù)
dataSource.setDriverClass ("com.mysql.jdbc.Driver" ) ;
dataSource.setJdbcUrl ("jdbc:mysql ://localhost:3306/test" ) ;
datasource.setUser ("root");
dataSource.setPassword ("root");
//獲得連接對(duì)象
Connection connection = dataSource.getConnection ();
system.out.println (connection) ;
創(chuàng)建Druid連接池
@Test
public void testDruid ( ) throws Exception {
//創(chuàng)建數(shù)據(jù)源
DruidDataSource dataSource = new DruidDatasource () ;
//設(shè)置數(shù)據(jù)庫(kù)連接參數(shù)
dataSource.setDriverclassName ("com.mysql.jdbc .Driver") ;
datasource.setUrl ("jdbc:mysql : //localhost:3306/test") ;
datasource.setUsername ("root") ;
datasource.setPassword ("root" ) ;
//獲得連接對(duì)象
connection connection = dataSource.getConnection ( ) ;
System.out.println (connection) ;
)
3、提取jdbc.properties配置文件
jdbc .driver=com.mysql.jdbc.Driver jdbc.url=jdbc :mysql://localhost:3306/test jdbc.username=root jdbc.password=root
4、讀取jdbc.properties配置文件創(chuàng)建連接池
@Test
//測(cè)試手動(dòng)創(chuàng)建 c3p0 數(shù)據(jù)源(加載properties配置文件)
public void test3() throws Exception {
//讀取配置文件
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String driver = rb.getString("jdbc.driver");
String url = rb.getString("jdbc.url");
String username = rb.getString("jdbc.username");
String password = rb.getString("jdbc.password");
//創(chuàng)建數(shù)據(jù)源對(duì)象 設(shè)置連接參數(shù)
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
Spring配置數(shù)據(jù)源
可以將DataSource的創(chuàng)建權(quán)交由Spring容器去完成
DataSource有無(wú)參構(gòu)造方法,而Spring默認(rèn)就是通過(guò)無(wú)參構(gòu)造方法實(shí)例化對(duì)象的
DataSource要想使用需要通過(guò)set方法設(shè)置數(shù)據(jù)庫(kù)連接信息,而Spring可以通過(guò)set方法進(jìn)行字符串注入
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />
<property name="user" value="root"/>
<property name="password" value=" root"/>
</bean>
測(cè)試從容器當(dāng)中獲取數(shù)據(jù)源
ApplicationContext applicationContext = new ClassPathXmlApplicationContext ( "applicationContext.xml" ) ; DataSource dataSource = ( DataSource) applicationcontext. getBean ( "dataSource" ) ; Connection connection = dataSource.getConnection ( ) ; System.out.println ( connection) ;
抽取jdbc配置文件
applicationContext.xml加載jdbc.properties配置文件獲得連接信息。
首先,需要引入context命名空間和約束路徑:
命名空間: xmIns:context="http://www.springframework.org/schema/context"
約束路徑: http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<context:property-placeholder location=" classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverclass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username} "/>
<property name="password" value="${jdbc.password}"/>
</bean>
Spring容器加載properties文件
<context:property-placeholder location="xx.properties" />
<property name=" " value="${key} " />
Spring注解開(kāi)發(fā)
Spring原始注解
Spring是輕代碼而重配置的框架,配置比較繁重,影響開(kāi)發(fā)效率,所以注解開(kāi)發(fā)是一種趨勢(shì),注解代替xml配置
文件可以簡(jiǎn)化配置,提高開(kāi)發(fā)效率。
Spring原始注解主要是替代<Bean>的配置

注意:
使用注解進(jìn)行開(kāi)發(fā)時(shí),需要在applicationContext.xml中配置組件掃描,作用是指定哪個(gè)包及其子包下的Bean需要進(jìn)行掃描以便識(shí)別使用注解配置的類(lèi)、字段和方法。
<!--注解的組件掃描--> <context:component-scan base-package="com.longdi "></context: component-scan>
使用@Compont或@Repository標(biāo)識(shí)UserDaolmpl需要Spring進(jìn)行實(shí)例化。
/ / @Component ( "userDao")
@Repository ("userDao")
public class UserDaoImpl implements UserDao {
@override
public void save ( ) {
system.out.println ( "save running . . . ..." ) ;
}
使用@Autowired或者@Autowired+@Qulifier或者@Resource進(jìn)行userDao的注入
// @Component ( "userservice ")
@service ( "userservice" )
public class UserserviceImpl implements UserService {
/*@Autowired
CQualifier ( "userDao")*/
@Resource (name= "userDao" )
private UserDao userDao;
@override
public void save ( ) {
userDao.save ( ) ;
}
)
使用@Value進(jìn)行字符串的注入
@Repository ( "userDao")
public class UserDaoImpl implements UserDao {
@value("注入普通數(shù)據(jù)")
private string str;
@value ("${jdbc.driver} ")
private string driver;
@override
public void save () {
system.out.println (str) ;
system.out.println (driver) ;
system.out.println ("save running......") ;
)
使用@Scope標(biāo)注Bean的范圍
// @scope ( "prototype ")
@Scope ( "singleton" )
public class UserDaoImpl implements UserDao {
//此處省略代碼
)
使用@PostConstruct標(biāo)注初始化方法,使用@PreDestroy標(biāo)注銷(xiāo)毀方法
@PostConstruct
public void init () {
system.out.println ("初始化方法...." );
}
@PreDestroy
public void destroy () {
system.out.println ("銷(xiāo)毀方法....." );
)
Spring新注解
使用上面的注解還不能全部替代xml配置文件,還需要使用注解替代的配置如下:
非自定義的Bean的配置: <bean>
加載properties文件的配置:<context:property-placeholder>
組件掃描的配置: <context:component-scan>
引入其他文件:<import>

@Configuration
@ComponentScan
@lmport
@Configuration
@componentScan ("com.longdi" )
@Import ({DataSourceConfiguration.class})
public class SpringConfiguration {
)
@PropertySource
@value
@Propertysource ( "classpath:jdbc.properties" )
public class DataSourceConfiguration {
@value ("${jdbc.driver}")
private string driver ;
@value ("${jdbc.ur1 }")
private string url;
@value ("${jdbc.username}")
private string username ;
@value ("${jdbc.password]")
private string password;
@Bean
Bean (name="dataSource " )
public DataSource getDataSource () throws PropertyvetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource ( ) ;
datasource.setDriverclass (driver) ;
datasource.setJdbcUrl (url) ;
datasource.setUser (username ) ;
dataSource.setPassword(password) ;
return dataSource;
測(cè)試加載核心配置類(lèi)創(chuàng)建Spring容器
Test
public void testAnnoConfiguration ( ) throws Exception {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext (SpringConfiguration.class) ;
UserService userService = (UserService)applicationContext.getBean ("userService");
userService.save () ;
Datasource dataSource = (Datasource)applicationContext.getBean ("dataSource" ) ;
Connection connection = dataSource.getConnection() ;
System.out.println (connection);
Spring整合Junit
原始Junit測(cè)試Spring的問(wèn)題
在測(cè)試類(lèi)中,每個(gè)測(cè)試方法都有以下兩行代碼:
ApplicationContext ac = new ClassPathxmlApplicationContext ( "bean.xml ");
IAccountService as = ac.getBean ("accountservice",IAccountService.class)
這兩行代碼的作用是獲取容器,如果不寫(xiě)的話,直接會(huì)提示空指針異常。所以又不能輕易刪掉。
讓SpringJunit負(fù)責(zé)創(chuàng)建Spring容器,但是需要將配置文件的名稱(chēng)告訴它
將需要進(jìn)行測(cè)試Bean直接在測(cè)試類(lèi)中進(jìn)行注入
Spring集成Junit步驟
1、導(dǎo)入spring集成Junit的坐標(biāo)
2、使用@Runwith注解替換原來(lái)的運(yùn)行期
3、使用@contextConfiguration指定配置文件或配置類(lèi)
4、使用@Autowired注入需要測(cè)試的對(duì)象
5、創(chuàng)建測(cè)試方法進(jìn)行測(cè)試
1、導(dǎo)入spring集成Junit的坐標(biāo)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2、使用@Runwith注解替換原來(lái)的運(yùn)行期
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}
3、使用@contextConfiguration指定配置文件或配置類(lèi)
@RunWith(SpringJUnit4ClassRunner.class)
//加載Spring核心配置文件
//@ContextConfiguration("classpath:applicationContext.xml")
//加載Spring核心配置類(lèi)
@ContextConfiguration(classes = {SpringCofiguration.class})
public class SpringJunitTest {
4、使用@Autowired注入需要測(cè)試的對(duì)象
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringCofiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
}
5、創(chuàng)建測(cè)試方法進(jìn)行測(cè)試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringCofiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void test1() throws SQLException {
userService.save();
}
}
到此這篇關(guān)于Java Spring詳解如何配置數(shù)據(jù)源注解開(kāi)發(fā)以及整合Junit的文章就介紹到這了,更多相關(guān)Java Spring內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JAVA正則表達(dá)式過(guò)濾文件的實(shí)現(xiàn)方法
這篇文章主要介紹了JAVA正則表達(dá)式過(guò)濾文件的實(shí)現(xiàn)方法的相關(guān)資料,希望通過(guò)本文大家能夠掌握理解這部分內(nèi)容,需要的朋友可以參考下2017-09-09
Java分布式學(xué)習(xí)之Kafka消息隊(duì)列
Kafka是由Apache軟件基金會(huì)開(kāi)發(fā)的一個(gè)開(kāi)源流處理平臺(tái),由Scala和Java編寫(xiě)。Kafka是一種高吞吐量的分布式發(fā)布訂閱消息系統(tǒng),它可以處理消費(fèi)者在網(wǎng)站中的所有動(dòng)作流數(shù)據(jù)2022-07-07
Mybatis批量插入Oracle數(shù)據(jù)的方法實(shí)例
在開(kāi)發(fā)中或多或少都會(huì)遇到數(shù)據(jù)批量插入的功能,最近我在做項(xiàng)目的過(guò)程中就遇到了這樣一個(gè)問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于Mybatis批量插入Oracle數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-01-01
springboot自定義starter方法及注解實(shí)例
這篇文章主要為大家介紹了springboot自定義starter方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
Java+opencv3.2.0實(shí)現(xiàn)hough直線檢測(cè)
這篇文章主要為大家詳細(xì)介紹了Java+opencv3.2.0之hough直線檢測(cè),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02

