Spring 黑馬程序員四天筆記(第二天:IOC、增刪改查)

第1章 案例:使用 spring 的 IoC 的實現賬戶的CRUD

1.1 需求和技術要求

實現賬戶的 CRUD 操作

1.1.2 技術要求

使用 spring 的 IoC 實現對象的管理 使用 DBAssit 作爲持久層解決方案使用 c3p0 數據源

1.2 環境搭建

1.2.1 拷貝jar包

1.2.2 創建數據庫和編寫實體類

create table account(
    id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
/**
* 賬戶的實體類
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0 */
public class Account implements Serializable {
private Integer id; private String name;
 
private Float money; public Integer getId() {
return id; }
public void setId(Integer id) {
this.id = id; }
public String getName() { return name;
}
public void setName(String name) {
this.name = name; }
public Float getMoney() {
return money; }
public void setMoney(Float money) { this.money = money;
} }

1.2.3 編寫持久層代碼

/**
* 賬戶的持久層接口
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/
public interface IAccountDao {
/**
* 保存
* @param account
*/
void save(Account account);
/**
* 更新
* @param account
*/
void update(Account account);
/**
* 刪除
* @param accountId */
void delete(Integer accountId);
/**
* 根據id查詢
* @param accountId
* @return */
Account findById(Integer accountId);
/**
* 查詢所有 * @return */
List<Account> findAll();
}
public class AccountDaoImpl implements IAccountDao { 
private DBAssit dbAssit;
public void setDbAssit(DBAssit dbAssit) { 
this.dbAssit = dbAssit;
}
@Override
public void save(Account account) {
dbAssit.update("insert into
account(name,money)values(?,?)",account.getName(),account.getMoney()); }
@Override
public void update(Account account) {
dbAssit.update("update account set name=?,money=? where
id=?",account.getName(),account.getMoney(),account.getId()); }
@Override
public void delete(Integer accountId) {
dbAssit.update("delete from account where id=?",accountId); }
@Override
public Account findById(Integer accountId) {
return dbAssit.query("select * from account where id=?",new
BeanHandler<Account>(Account.class),accountId);
}
@Override
public List<Account> findAll() {
return dbAssit.query("select * from account where id=?",new
BeanListHandler<Account>(Account.class));
} }

1.2.4 編寫業務層代碼

/**
* 賬戶的業務層接口
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/
public interface IAccountService {
/**
* 保存賬戶
* @param account
*/
void saveAccount(Account account);
/**
* 更新賬戶
* @param account */
void updateAccount(Account account);
/**
* 刪除賬戶
* @param account */
void deleteAccount(Integer accountId);
/**
* 根據 id 查詢賬戶
* @param accountId * @return
*/
Account findAccountById(Integer accountId);
/**
* 查詢所有賬戶 * @return
*/
List<Account> findAllAccount();
}
/**
* 賬戶的業務層實現類
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
public class AccountServiceImpl implements IAccountService { private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao; }
@Override
public void saveAccount(Account account) { accountDao.save(account);
}
@Override
public void updateAccount(Account account) { accountDao.update(account);
}
@Override
public void deleteAccount(Integer accountId) { accountDao.delete(accountId);
}
@Override
public Account findAccountById(Integer accountId) { return accountDao.findById(accountId);
}
@Override
public List<Account> findAllAccount() {
return accountDao.findAll(); }
}

1.2.5 創建並編寫配置文件

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> 
</beans>

1.3 配置步驟

1.3.1 配置對象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置 service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property> </bean>
<!-- 配置 dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"> 
<property name="dbAssit" ref="dbAssit"></property>
</bean>
<!-- 配置 dbAssit 此處我們只注入了數據源,表明每條語句獨立事務--> 
<bean id="dbAssit" class="com.itheima.dbassit.DBAssit">
<property name="dataSource" ref="dataSource"></property> </bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property> 
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property> 
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>

1.4 測試案例

1.4.1 測試類代碼

/**
* 測試類
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
public class AccountServiceTest {
/**
* 測試保存
*/
@Test
public void testSaveAccount() { Account account = new Account(); account.setName("黑馬程序員");
account.setMoney(100000f);
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); as.saveAccount(account);
} /**
* 測試查詢一個 */
@Test
public void testFindAccountById() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class); 
Account account = as.findAccountById(1);
System.out.println(account);
}
/**
* 測試更新 */
@Test
public void testUpdateAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); 
Account account = as.findAccountById(1);
account.setMoney(20301050f);
as.updateAccount(account); }
/**
* 測試刪除
*/
@Test
public void testDeleteAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
as.deleteAccount(1); }
/**
* 測試查詢所有
*/
@Test
public void testFindAllAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); List<Account> list = as.findAllAccount();
for(Account account : list) { System.out.println(account);
} }
}

1.4.2 分析測試了中的問題

通過上面的測試類,我們可以看出,每個測試方法都重新獲取了一次 spring 的核心容器,造成了不必要的重複代碼,增加了我們開發的工作量。這種情況,在開發中應該避免發生。 有些同學可能想到了,我們把容器的獲取定義到類中去。例如:

/**
* 測試類
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
public class AccountServiceTest {
private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
private   as = ac.getBean("accountService",   .class); }

這種方式雖然能解決問題,但是扔需要我們自己寫代碼來獲取容器。 能不能測試時直接就編寫測試方法,而不需要手動編碼來獲取容器呢?

請在今天的最後一章節找答案。

第2章 基於註解的 IOC 配置

2.1明確:寫在最前

學習基於註解的 IoC 配置,大家腦海裏首先得有一個認知,即註解配置和 xml 配置要實現的功能都是一樣

的,都是要降低程序間的耦合。只是配置的形式不一樣。
關於實際的開發中到底使用 xml 還是註解,每家公司有着不同的使用習慣。所以這兩種配置方式我們都需要掌

握。
我們在講解註解配置時,採用上一章節的案例,把 spring 的 xml 配置內容改爲使用註解逐步實現。

2.2環境搭建

2.2.1 第一步:拷貝必備 jar 包到工程的 lib 目錄。

注意:在基於註解的配置中,我們還要多拷貝一個 aop 的 jar 包。如下圖:

2.2.2 第二步:使用@Component註解配置管理的資源

/**
* 賬戶的業務層實現類
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
@Component("accountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao;
} }
/**
* 賬戶的持久層實現類 * @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
@Component("accountDao")
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit; }

注意:

1、當我們使用註解注入時,set 方法不用寫

2.2.3 第三步:創建 spring 的 xml 配置文件並開啓對註解的支持

注意:

基於註解整合時,導入約束時需要多導入一個 context 名稱空間下的約束。

由於我們使用了註解配置,此時不能在繼承 JdbcDaoSupport,需要自己配置一個 JdbcTemplate

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 告知 spring 創建容器時要掃描的包 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
<!-- 配置 dbAssit -->
<bean id="dbAssit" class="com.itheima.dbassit.DBAssit">
<property name="dataSource" ref="dataSource"></property> </bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
<property name="driverClass" value="com.mysql.jdbc.Driver"></property> 
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property> </bean>
</beans>

2.3常用註解

2.3.1 用於創建對象的

相當於:<bean id="" class="">

2.3.1.1 @Component

作用:

把資源讓 spring 來管理。相當於在 xml 中配置一個 bean。

屬性:

value:指定 bean 的 id。如果不指定 value 屬性,默認 bean 的 id 是當前類的類名。首字母小寫。

2.3.1.2 @Controller @Service @Repository

他們三個註解都是針對一個的衍生註解,他們的作用及屬性都是一模一樣的。 他們只不過是提供了更加明確的語義化。

@Controller: 一般用於表現層的註解。 @Service: 一般用於業務層的註解。

@Repository: 一般用於持久層的註解。 細節:如果註解中有且只有一個屬性要賦值時,且名稱是 value,value 在賦值是可以不寫。

2.3.2 用於注入數據的

相當於:<property name="" ref="">

<property name="" value="">

2.3.2.1 @Autowired

作用:

自動按照類型注入。當使用註解注入屬性時,set 方法可以省略。它只能注入其他 bean 類型。當有多個 類型匹配時,使用要注入的對象變量名稱作爲 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到 就報錯。

2.3.2.2 @Qualifier

作用:

在自動按照類型注入的基礎之上,再按照 Bean 的 id 注入。它在給字段注入時不能獨立使用,必須和

@Autowire 一起使用;但是給方法參數注入時,可以獨立使用。 屬性:

value:指定 bean 的 id。

 

2.3.2.3 @Resource

作用:

直接按照 Bean 的 id 注入。它也只能注入其他 bean 類型。

屬性:

name:指定 bean 的 id。

2.3.2.4 @Value

作用:

注入基本數據類型和 String 類型數據的 屬性:

value:用於指定值

2.3.3 用於改變作用範圍的:

相當於:<bean id="" class="" scope="">

2.3.3.1 @Scope

作用:

指定 bean 的作用範圍。 屬性:

value:指定範圍的值。

取值:singleton prototype request session globalsession

 

2.3.4 和生命週期相關的:(瞭解)

相當於:<bean id="" class="" init-method="" destroy-method="" />

2.3.4.1 @PostConstruct

作用:

用於指定初始化方法。

2.3.4.2 @PreDestroy

作用:

用於指定銷燬方法。

2.3.5 關於 Spring 註解和 XML 的選擇問題

註解的優勢:

配置簡單,維護方便(我們找到類,就相當於找到了對應的配置)。

XML 的優勢: 修改時,不用改源碼。不涉及重新編譯和部署。

Spring 管理 Bean 方式的比較:

2.4spring 管理對象細節

基於註解的spring IoC配置中,bean對象的特點和基於XML配置是一模一樣的。

2.5spring 的純註解配置

寫到此處,基於註解的 IoC 配置已經完成,但是大家都發現了一個問題:我們依然離不開 spring 的 xml 配 置文件,那麼能不能不寫這個 bean.xml,所有配置都用註解來實現呢?

當然,同學們也需要注意一下,我們選擇哪種配置的原則是簡化開發和配置方便,而非追求某種技術。

2.5.1 待改造的問題

我們發現,之所以我們現在離不開 xml 配置文件,是因爲我們有一句很關鍵的配置:

<!-- 告知spring框架在,讀取配置文件,創建容器時,掃描註解,依據註解創建對象,並存入容器中 --> <context:component-scan base-package="com.itheima"></context:component-scan> 如果他要也能用註解配置,那麼我們就離脫離 xml 文件又進了一步。
另外,數據源和 JdbcTemplate 的配置也需要靠註解來實現。
<!-- 配置 dbAssit -->
<bean id="dbAssit" class="com.itheima.dbassit.DBAssit">
<property name="dataSource" ref="dataSource"></property> </bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property> 
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>

2.5.2 新註解說明

2.5.2.1 @Configuration

作用:

用於指定當前類是一個 spring 配置類,當創建容器時會從該類上加載註解。獲取容器時需要使用

AnnotationApplicationContext(有@Configuration 註解的類.class)。

屬性:

value:用於指定配置類的字節碼

示例代碼:

/**
* spring的配置類,相當於bean.xml文件
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/
@Configuration
public class SpringConfiguration { }

注意:

我們已經把配置文件用類來代替了,但是如何配置創建容器時要掃描的包呢? 請看下一個註解。

2.5.2.2 @ComponentScan

作用:

用於指定 spring 在初始化容器時要掃描的包。作用和在 spring 的 xml 配置文件中的:

<context:component-scan base-package="com.itheima"/>是一樣的。

屬性:

basePackages:用於指定要掃描的包。和該註解中的 value 屬性作用一樣。

示例代碼:

/**
* spring的配置類,相當於bean.xml文件
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
@Configuration @ComponentScan("com.itheima") public class SpringConfiguration {
}

注意:

我們已經配置好了要掃描的包,但是數據源和 JdbcTemplate 對象如何從配置文件中移除呢?

請看下一個註解。

2.5.2.3 @Bean

作用:

該註解只能寫在方法上,表明使用此方法創建一個對象,並且放入 spring 容器。

屬性:

name:給當前@Bean 註解方法創建的對象指定一個名稱(即 bean 的 id)。

示例代碼:

**
* 連接數據庫的配置類
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
public class JdbcConfig {
/**
* 創建一個數據源,並存入 spring 容器中
* @return
*/
@Bean(name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setUser("root");
ds.setPassword("1234"); ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///spring_day02");
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
} }
/**
* 創建一個 DBAssit,並且也存入 spring 容器中
* @param dataSource * @return
*/
@Bean(name="dbAssit")
public   createDBAssit(DataSource dataSource) { return new DBAssit(dataSource);
}
DBAssit
}

注意:

我們已經把數據源和 DBAssit 從配置文件中移除了,此時可以刪除 bean.xml 了。 但是由於沒有了配置文件,創建數據源的配置又都寫死在類中了。如何把它們配置出來呢? 請看下一個註解。

2.5.2.4 @PropertySource

作用:

用於加載.properties 文件中的配置。例如我們配置數據源時,可以把連接數據庫的信息寫到 properties 配置文件中,就可以使用此註解指定 properties 配置文件的位置。

屬性:

value[]:用於指定 properties 文件位置。如果是在類路徑下,需要寫上 classpath:

示例代碼:

/**
* 連接數據庫的配置類
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/
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;
/**
* 創建一個數據源,並存入 spring 容器中 * @return
*/
@Bean(name="dataSource")
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);
} }
}

jdbc.properties 文件:

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/day44_ee247_spring
jdbc.username=root
jdbc.password=1234

注意:

此時我們已經有了兩個配置類,但是他們還沒有關係。如何建立他們的關係呢? 請看下一個註解。

2.5.2.5 @Import

作用:

用於導入其他配置類,在引入其他配置類時,可以不用再寫@Configuration 註解。當然,寫上也沒問題。

屬性:

value[]:用於指定其他配置類的字節碼。

示例代碼:

@Configuration
@ComponentScan(basePackages = "com.itheima.spring") 
@Import({ JdbcConfig.class})
public class SpringConfiguration {
}
@Configuration 
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig{ }

注意:

我們已經把要配置的都配置好了,但是新的問題產生了,由於沒有配置文件了,如何獲取容器呢? 請看下一小節。

2.5.2.6 通過註解獲取容器:

 ApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfiguration.class);

 

2.5.3 工程結構圖

第3章 Spring 整合 Junit[掌握]

3.1 測試類中的問題和解決思路

3.1.1 問題

在測試類中,每個測試方法都有以下兩行代碼:

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class);

這兩行代碼的作用是獲取容器,如果不寫的話,直接會提示空指針異常。所以又不能輕易刪掉。

3.1.2 解決思路分析

針對上述問題,我們需要的是程序能自動幫我們創建容器。一旦程序能自動爲我們創建 spring 容器,我們就 無須手動創建了,問題也就解決了。

我們都知道,junit 單元測試的原理(在 web 階段課程中講過),但顯然,junit 是無法實現的,因爲它自 己都無法知曉我們是否使用了 spring 框架,更不用說幫我們創建 spring 容器了。不過好在,junit 給我們暴露 了一個註解,可以讓我們替換掉它的運行器。

這時,我們需要依靠 spring 框架,因爲它提供了一個運行器,可以讀取配置文件(或註解)來創建容器。我 們只需要告訴它配置文件在哪就行了。

3.2配置步驟

3.2.1 第一步:拷貝整合 junit 的必備 jar 包到 lib 目錄

此處需要注意的是,導入 jar 包時,需要導入一個 spring 中 aop 的 jar 包。

3.2.2 第二步:使用@RunWith 註解替換原有運行器

/**
* 測試類
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest { }

3.2.3 第三步:使用@ContextConfiguration 指定 spring 配置文件的位置

/**
* 測試類
* @author 黑馬程序員
* @Company http://www.ithiema.com
* @Version 1.0
*/ @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"}) 
public class AccountServiceTest {
}

@ContextConfiguration

註解:
locations 屬性:用於指定配置文件的位置。如果是類路徑下,需要用 classpath:表明 classes

屬性:

用於指定註解的類。當不使用 xml 配置時,需要用此屬性指定註解類的位置。

3.2.4 第四步:使用@Autowired 給測試類中的變量注入數據

/**
* 測試類
* @author 黑馬程序員
* @Company http://www.ithiema.com * @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ; 
}

3.3爲什麼不把測試類配到 xml 中

在解釋這個問題之前,先解除大家的疑慮,配到 XML 中能不能用呢?

答案是肯定的,沒問題,可以使用。 那麼爲什麼不採用配置到 xml 中的方式呢?

這個原因是這樣的:
第一:當我們在 xml 中配置了一個 bean,spring 加載配置文件創建容器時,就會創建對象。 第二:測試類只是我們在測試功能時使用,而在項目中它並不參與程序邏輯,也不會解決需求上的問題,所以創建完了,並沒有使用。那麼存在容器中就會造成資源的浪費。 所以,基於以上兩點,我們不應該把測試配置到 xml 文件中。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章