Java Spring詳解如何配置數(shù)據(jù)源注解開發(fā)以及整合Junit
Spring數(shù)據(jù)源的配置
數(shù)據(jù)源(連接池)的作用
數(shù)據(jù)源(連接池)是提高程序性能如出現(xiàn)的
事先實例化數(shù)據(jù)源,初始化部分連接資源
使用連接資源時從數(shù)據(jù)源中獲取
使用完畢后將連接資源歸還給數(shù)據(jù)源
常見的數(shù)據(jù)源(連接池):DBCP、C3PO、BoneCP、Druid等
數(shù)據(jù)源的開發(fā)步驟
1、導入數(shù)據(jù)源的坐標和數(shù)據(jù)庫驅(qū)動坐標
2、創(chuàng)建數(shù)據(jù)源對象
3、設(shè)置數(shù)據(jù)源的基本連接數(shù)據(jù)
4、使用數(shù)據(jù)源獲取連接資源和歸還連接資源
手動創(chuàng)建數(shù)據(jù)源
1、導入c3p0和druid坐標,mysql數(shù)據(jù)庫驅(qū)動坐標
<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ù)庫連接參數(shù)
dataSource.setDriverClass ("com.mysql.jdbc.Driver" ) ;
dataSource.setJdbcUrl ("jdbc:mysql ://localhost:3306/test" ) ;
datasource.setUser ("root");
dataSource.setPassword ("root");
//獲得連接對象
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ù)庫連接參數(shù)
dataSource.setDriverclassName ("com.mysql.jdbc .Driver") ;
datasource.setUrl ("jdbc:mysql : //localhost:3306/test") ;
datasource.setUsername ("root") ;
datasource.setPassword ("root" ) ;
//獲得連接對象
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
//測試手動創(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ù)源對象 設(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有無參構(gòu)造方法,而Spring默認就是通過無參構(gòu)造方法實例化對象的
DataSource要想使用需要通過set方法設(shè)置數(shù)據(jù)庫連接信息,而Spring可以通過set方法進行字符串注入
<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>
測試從容器當中獲取數(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注解開發(fā)
Spring原始注解
Spring是輕代碼而重配置的框架,配置比較繁重,影響開發(fā)效率,所以注解開發(fā)是一種趨勢,注解代替xml配置
文件可以簡化配置,提高開發(fā)效率。
Spring原始注解主要是替代<Bean>的配置

注意:
使用注解進行開發(fā)時,需要在applicationContext.xml中配置組件掃描,作用是指定哪個包及其子包下的Bean需要進行掃描以便識別使用注解配置的類、字段和方法。
<!--注解的組件掃描--> <context:component-scan base-package="com.longdi "></context: component-scan>
使用@Compont或@Repository標識UserDaolmpl需要Spring進行實例化。
/ / @Component ( "userDao")
@Repository ("userDao")
public class UserDaoImpl implements UserDao {
@override
public void save ( ) {
system.out.println ( "save running . . . ..." ) ;
}
使用@Autowired或者@Autowired+@Qulifier或者@Resource進行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進行字符串的注入
@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標注Bean的范圍
// @scope ( "prototype ")
@Scope ( "singleton" )
public class UserDaoImpl implements UserDao {
//此處省略代碼
)
使用@PostConstruct標注初始化方法,使用@PreDestroy標注銷毀方法
@PostConstruct
public void init () {
system.out.println ("初始化方法...." );
}
@PreDestroy
public void destroy () {
system.out.println ("銷毀方法....." );
)
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;
測試加載核心配置類創(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測試Spring的問題
在測試類中,每個測試方法都有以下兩行代碼:
ApplicationContext ac = new ClassPathxmlApplicationContext ( "bean.xml ");
IAccountService as = ac.getBean ("accountservice",IAccountService.class)
這兩行代碼的作用是獲取容器,如果不寫的話,直接會提示空指針異常。所以又不能輕易刪掉。
讓SpringJunit負責創(chuàng)建Spring容器,但是需要將配置文件的名稱告訴它
將需要進行測試Bean直接在測試類中進行注入
Spring集成Junit步驟
1、導入spring集成Junit的坐標
2、使用@Runwith注解替換原來的運行期
3、使用@contextConfiguration指定配置文件或配置類
4、使用@Autowired注入需要測試的對象
5、創(chuàng)建測試方法進行測試
1、導入spring集成Junit的坐標
<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注解替換原來的運行期
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}
3、使用@contextConfiguration指定配置文件或配置類
@RunWith(SpringJUnit4ClassRunner.class)
//加載Spring核心配置文件
//@ContextConfiguration("classpath:applicationContext.xml")
//加載Spring核心配置類
@ContextConfiguration(classes = {SpringCofiguration.class})
public class SpringJunitTest {
4、使用@Autowired注入需要測試的對象
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringCofiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
}
5、創(chuàng)建測試方法進行測試
@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ù)源注解開發(fā)以及整合Junit的文章就介紹到這了,更多相關(guān)Java Spring內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis批量插入Oracle數(shù)據(jù)的方法實例
在開發(fā)中或多或少都會遇到數(shù)據(jù)批量插入的功能,最近我在做項目的過程中就遇到了這樣一個問題,下面這篇文章主要給大家介紹了關(guān)于Mybatis批量插入Oracle數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-01-01
Java+opencv3.2.0實現(xiàn)hough直線檢測
這篇文章主要為大家詳細介紹了Java+opencv3.2.0之hough直線檢測,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02

