目錄
◆ Spring配置數(shù)據(jù)源
◆ Spring注解開發(fā)
◆ Spring整合Junit
Spring配置數(shù)據(jù)源
◆ 數(shù)據(jù)源(連接池)的作用
數(shù)據(jù)源(連接池)是提高程序性能如出現(xiàn)的事先實(shí)例化數(shù)據(jù)源,初始化部分連接資源,使用連接資源時(shí)從數(shù)據(jù)源中獲取,使用完畢后將連接資源歸還給數(shù)據(jù)源。
常見的數(shù)據(jù)源(連接池) :DBCP、C3P0、BoneCP、Druid等
◆ 數(shù)據(jù)源的開發(fā)步驟
①導(dǎo)入數(shù)據(jù)源的坐標(biāo)和數(shù)據(jù)庫(kù)驅(qū)動(dòng)坐標(biāo)
②創(chuàng)建數(shù)據(jù)源對(duì)象
③設(shè)置數(shù)據(jù)源的基本連接數(shù)據(jù)
④使用數(shù)據(jù)源獲取連接資源和歸還連接資源
◆ C3P0代碼演示
◆ Druid代碼演示
◆ 抽取jdbc.properties配置文件解耦合
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.user name=root
jdbc.password=root
@Test
//測(cè)試手動(dòng)創(chuàng)建c3p0數(shù)據(jù)源(加載properties配置文件)
public void test 3() throws Exception{
//讀取配置文件
ResourceBundlerb=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();
connection.close();
}
◆ spring配置數(shù)據(jù)源
● 1)導(dǎo)坐標(biāo)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
● 2)創(chuàng)建數(shù)據(jù)源對(duì)象
因數(shù)據(jù)源對(duì)象時(shí)導(dǎo)入第三方j(luò)ar包,這個(gè)Dao層是jar包提供好的
● 3)設(shè)置數(shù)據(jù)源的基本連接數(shù)據(jù)(創(chuàng)建配置文件)
創(chuàng)建XML里面的spring config配置文件,在resources目錄下
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource”>
<property name="driverClass” value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl” value="jdbc:mysql://localhost:3306/test">/property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
@Test
//測(cè)試Spring容器產(chǎn)生數(shù)據(jù)源對(duì)象
public void test 4() throws Exception{
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource=app.getBean(DataSource.class);
Connection connection=dataSource.getConnection();
System.out.println(connection);
connection.close();
}
Spring注解開發(fā)
◆ Spring原始注解
Spring是輕代碼而重配置的框架,配置比較繁重,影響開發(fā)效率,所以注解開發(fā)是一種趨勢(shì),注解代替xml配置文件可以簡(jiǎn)化配置,提高開發(fā)效率。
● Spring原始注解主要是替代<Bean>的配置
| 注解 |
說明 |
| @Component |
使用在類上用于實(shí)例化Bean |
| @Controller |
使用在web層類上用于實(shí)例化Bean |
| @Service |
使用在service層類上用于實(shí)例化Bean |
| @Repository |
使用在dao層類上用于實(shí)例化Bean |
| @Autowired |
使用在字段上用于根據(jù)類型依賴注入 |
| @Qualifier |
結(jié)合@Autowired一起使用用于根據(jù)名稱進(jìn)行依賴注入 |
| @Resource |
相當(dāng)于@Autowired+@Qualifier, 按照名稱進(jìn)行注入 |
| @Value |
注入普通屬性 |
| @Scope |
標(biāo)注Bean的作用范圍 |
| @PostConstruct |
使用在方法上標(biāo)注該方法是Bean的初始化方法 |
| @PreDestroy |
使用在方法上標(biāo)注該方法是Bean的銷毀方法 |
● Spring注解開發(fā)時(shí)需要配組件掃描
注意:
使用注解進(jìn)行開發(fā)時(shí),需要在applicationContext.xml中配置組件掃描,作用是指定哪個(gè)包及其子包下的Bean需要進(jìn)行掃描以便識(shí)別使用注解配置的類、字段和方法。
<!--注解的組件掃描-->
<context:component-scan base-package="com.itheima"></context:component-scan>
◆ Spring新注解
使用上面的注解還不能全部替代xml配置文件,還需要使用注解替代的配置如下:
非自定義的Bean的配置:<bean>
加載properties文件的配置:<context:property-placeholder>
組件掃描的配置:<context:component-scan>
引入其他文件:<import>
| 注解 |
說明 |
| @Configuration |
用于指定當(dāng)前類是一個(gè)Spring配置類,當(dāng)創(chuàng)建容器時(shí)會(huì)從該類上加載注解 |
| @ComponentScan |
用于指定Spring在初始化容器時(shí)要掃描的包。作用和在Spring的xml配置文件中的<context:component-scanbase-package="com.itheima"/>一樣 |
| @Bean |
使用在方法上, 標(biāo)注將該方法的返回值存儲(chǔ)到Spring容器中 |
| @PropertySource |
用于加載.properties文件中的配置 |
| @Import |
用于導(dǎo)入其他配置類 |
全注解開發(fā)代碼演示
public static void main(String[]args) {
//ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml") ;
ApplicationContext app=new AnnotationConfigApplicationContext(SpringCofiguration.class);
UserService userService=app.getBean(UserService.class);
userService.save();
}
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
/**
* 該類是一個(gè)配置類,它的作用和bean.xml是一樣的
* spring中的新注解
* Configuration
* 作用:指定當(dāng)前類是一個(gè)配置類
* 細(xì)節(jié):當(dāng)配置類作為AnnotationConfigApplicationContext對(duì)象創(chuàng)建的參數(shù)時(shí),該注解可以不寫。
* ComponentScan
* 作用:用于通過注解指定spring在創(chuàng)建容器時(shí)要掃描的包
* 屬性:
* value:它和basePackages的作用是一樣的,都是用于指定創(chuàng)建容器時(shí)要掃描的包。
* 我們使用此注解就等同于在xml中配置了:
* <context:component-scan base-package="com.itheima"></context:component-scan>
* Bean
* 作用:用于把當(dāng)前方法的返回值作為bean對(duì)象存入spring的ioc容器中
* 屬性:
* name:用于指定bean的id。當(dāng)不寫時(shí),默認(rèn)值是當(dāng)前方法的名稱
* 細(xì)節(jié):
* 當(dāng)我們使用注解配置方法時(shí),如果方法有參數(shù),spring框架會(huì)去容器中查找有沒有可用的bean對(duì)象。
* 查找的方式和Autowired注解的作用是一樣的
* Import
* 作用:用于導(dǎo)入其他的配置類
* 屬性:
* value:用于指定其他配置類的字節(jié)碼。
* 當(dāng)我們使用Import的注解之后,有Import注解的類就父配置類,而導(dǎo)入的都是子配置類
* PropertySource
* 作用:用于指定properties文件的位置
* 屬性:
* value:指定文件的名稱和路徑。
* 關(guān)鍵字:classpath,表示類路徑下
*/
//@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
* 和spring連接數(shù)據(jù)庫(kù)相關(guān)的配置類
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 用于創(chuàng)建一個(gè)QueryRunner對(duì)象
* @param dataSource
* @return
*/
@Bean(name="runner")
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 創(chuàng)建數(shù)據(jù)源對(duì)象
* @return
*/
@Bean(name="ds2")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
@Bean(name="ds1")
public DataSource createDataSource1(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
ds.setUser(username);
ds.setPassword(password);
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
Spring整合Junit
◆ 原始Junit測(cè)試Spring的問題
在測(cè)試類中,每個(gè)測(cè)試方法都有以下兩行代碼:
ApplicationContext ac = new ClassPathxmlApplicationContext("bean.xml");
IAccountService as = ac.get Bean("accountService", IAccount Service.class);
這兩行代碼的作用是獲取容器,如果不寫的話,直接會(huì)提示空指針異常。所以又不能輕易刪掉。
◆ Spring集成Junit步驟
①導(dǎo)入spring集成Junit的坐標(biāo)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE <version>
</dependency>
②使用@Run with注解替換原來的運(yùn)行期
③使用@ContextConfiguration指定配置文件或配置類
④使用@Autowired注入需要測(cè)試的對(duì)象
⑤創(chuàng)建測(cè)試方法進(jìn)行測(cè)試
代碼演示:
package com.itheima.test;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* 使用Junit單元測(cè)試:測(cè)試我們的配置
* Spring整合junit的配置
* 1、導(dǎo)入spring整合junit的jar(坐標(biāo))
* 2、使用Junit提供的一個(gè)注解把原有的main方法替換了,替換成spring提供的@Runwith
* 3、告知spring的運(yùn)行器,spring和ioc創(chuàng)建是基于xml還是注解的,并且說明位置
* @ContextConfiguration
* locations:指定xml文件的位置,加上classpath關(guān)鍵字,表示在類路徑下
* classes:指定注解類所在地位置
* 當(dāng)我們使用spring 5.x版本的時(shí)候,要求junit的jar必須是4.12及以上
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService as = null;
@Test
public void testFindAll() {
//3.執(zhí)行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。