06-基于 XML 和注解 的 IOC 案例
生活随笔
收集整理的這篇文章主要介紹了
06-基于 XML 和注解 的 IOC 案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 一、pom.xml 配置
- 二、創建接口、數據庫表與實體類
- 1.數據庫表
- 2.實體類
- 3.數據訪問層
- Ⅰ 接口類
- Ⅱ 實現類
- 4.業務邏輯層
- Ⅰ 接口類
- Ⅱ 實現類
- 三、bean.xml
- 四、Test
- 五、基于注解
- 1. bean.xml
- 2. dao
- 3. service
新建一個 maven 工程
一、pom.xml 配置
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>spring05</groupId><artifactId>spring05</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><!-- https://mvnrepository.com/artifact/org.springframework/spring-context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.9.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils --><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.7</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>6.0.6</version></dependency><!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.4</version></dependency><!-- https://mvnrepository.com/artifact/junit/junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies></project>二、創建接口、數據庫表與實體類
1.數據庫表
create table account02(id int primary key auto_increment,name varchar(40),money float );insert into account02(name,money) values ('aaa',10),('bbb',100),('ccc',1000);2.實體類
創建 domain 文件夾
創建 Account 類生成get,set方法還有 tostring 方法
package com.domain;public class Account {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;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';} }3.數據訪問層
Ⅰ 接口類
package com.dao;import com.domain.Account;import java.util.List;/*** 描述:〈賬戶的持久層接口〉* @author zuiren* @create 2019/8/27* @since 1.0.0*/ public interface IAccountDao {/*** 查詢所有* @return*/List<Account> findAllAccount();/*** 查詢一個* @param accountId* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 修改* @param accountId*/void deleteAccount(Integer accountId); }Ⅱ 實現類
package com.dao.Impl;import com.domain.Account; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.SQLException; import java.util.List;/*** 描述:* 〈賬戶的持久層實現類〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/ public class IAccountDaoImpl implements com.dao.IAccountDao {private QueryRunner runner;public IAccountDaoImpl(QueryRunner runner) {this.runner = runner;}public List<Account> findAllAccount() {try {return runner.query("select *from account02",new BeanListHandler<Account>(Account.class));}catch (Exception e){throw new RuntimeException(e);}}public Account findAccountById(Integer accountId) {try {return runner.query("select *from account02 where id = ?",new BeanHandler<Account>(Account.class),accountId);}catch (Exception e){throw new RuntimeException(e);}}public void saveAccount(Account account) {try {runner.update("insert into account02(name,money) values(?,?)",account.getName(),account.getMoney());}catch (SQLException e){e.printStackTrace();}}public void updateAccount(Account account) {try {runner.update("update account02 set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}catch (SQLException e){e.printStackTrace();}}public void deleteAccount(Integer accountId) {try {runner.update("delete from account02 where id=?",accountId);}catch (SQLException e){e.printStackTrace();}} }4.業務邏輯層
Ⅰ 接口類
package com.service;import com.domain.Account;import java.util.List;/*** 描述:〈賬戶的業務層接口〉* @author zuiren* @create 2019/8/27* @since 1.0.0*/ public interface IAccountService {/*** 查詢所有* @return*/List<Account> findAllAccount();/*** 查詢一個* @param accountId* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 修改* @param accountId*/void deleteAccount(Integer accountId); }Ⅱ 實現類
package com.service.Impl;import com.dao.IAccountDao; import com.domain.Account; import com.service.IAccountService;import java.util.List;/*** 描述:* 〈賬戶的業務層實現類〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/ public class AccountServiceImpl implements IAccountService {private IAccountDao accountDao;public AccountServiceImpl(IAccountDao accountDao) {this.accountDao = accountDao;}public List<Account> findAllAccount() {return accountDao.findAllAccount();}public Account findAccountById(Integer accountId) {return accountDao.findAccountById(accountId);}public void saveAccount(Account account) {accountDao.saveAccount(account);}public void updateAccount(Account account) {accountDao.updateAccount(account);}public void deleteAccount(Integer accountId) {accountDao.deleteAccount(accountId);} }三、bean.xml
在 resources 文件夾下創建 bean.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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><!--配置 Service--><bean id="accountService" class="com.service.Impl.AccountServiceImpl"><constructor-arg ref="accountDao"/><!--注入 dao--></bean><!--配置 Dao--><bean id="accountDao" class="com.dao.Impl.IAccountDaoImpl"><!--注入QueryRunner--><constructor-arg ref="runner"/></bean><!--配置QueryRunner 默認為單例對象--><bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"><!--QueryRunner 可以帶參創建,也可以無參構造,有區別,你希望每條語句獨立一個事務,還是所有的語句在同一個事務中由于此處是單表,一條語句的 crud 的操作,所以此時可以選擇傳入數據源--><!--注入數據源--><constructor-arg name="ds" ref="dataSource"/></bean><!--配置數據源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!--連接數據庫的必備信息--><property name="driverClass" value="com.mysql.cj.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT"/><property name="user" value="root"/><property name="password" value="root"/></bean> </beans>四、Test
在 test 下創建 AccountServiceTest 類
package com.test;import com.domain.Account; import com.service.IAccountService; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;/*** 描述:* 〈使用 junit 單元測試:測試我們配置〉** @author zuiren* @create 2019/8/28* @since 1.0.0*/ public class AccountServiceTest {//1.獲取容器ApplicationContext ac=null;//2.得到業務層對象IAccountService as=null;@Beforepublic void init(){//1.獲取容器ac=new ClassPathXmlApplicationContext("bean.xml");//2.得到業務層對象as=ac.getBean("accountService",IAccountService.class);}@Testpublic void testFindAllAccount(){//3.執行方法List<Account> accounts = as.findAllAccount();for (Account account:accounts){System.out.println(account);}}@Testpublic void testFindAccountById(){//3.執行方法Account account=as.findAccountById(1);System.out.println(account);}@Testpublic void testSaveAccount(){//3.執行方法Account account=new Account();account.setName("卡茲克");account.setMoney(300);as.saveAccount(account);}@Testpublic void testUpdateAccount(){}@Testpublic void testDeleteAccount(){} }[TOC]
五、基于注解
1. bean.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:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><!--告知 spring 在創建容器時要掃描的白--><context:component-scan base-package="com"/><bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"><!--注入數據源--><constructor-arg name="ds" ref="dataSource"/></bean><!--配置數據源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!--連接數據庫的必備信息--><property name="driverClass" value="com.mysql.cj.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT"/><property name="user" value="root"/><property name="password" value="root"/></bean></beans>2. dao
package com.dao.Impl;import com.domain.Account; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;import java.sql.SQLException; import java.util.List;/*** 描述:* 〈賬戶的持久層實現類〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/ @Repository(value = "accountDao") public class IAccountDaoImpl implements com.dao.IAccountDao {@Autowiredprivate QueryRunner runner;public List<Account> findAllAccount() {try {return runner.query("select *from account02",new BeanListHandler<Account>(Account.class));}catch (Exception e){throw new RuntimeException(e);}}public Account findAccountById(Integer accountId) {try {return runner.query("select *from account02 where id = ?",new BeanHandler<Account>(Account.class),accountId);}catch (Exception e){throw new RuntimeException(e);}}public void saveAccount(Account account) {try {runner.update("insert into account02(name,money) values(?,?)",account.getName(),account.getMoney());}catch (SQLException e){e.printStackTrace();}}public void updateAccount(Account account) {try {runner.update("update account02 set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}catch (SQLException e){e.printStackTrace();}}public void deleteAccount(Integer accountId) {try {runner.update("delete from account02 where id=?",accountId);}catch (SQLException e){e.printStackTrace();}} }3. service
package com.service.Impl;import com.dao.IAccountDao; import com.domain.Account; import com.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service;import javax.annotation.Resource; import java.util.List;/*** 描述:* 〈賬戶的業務層實現類〉** @author zuiren* @create 2019/8/27* @since 1.0.0*/ @Service(value = "accountService") public class AccountServiceImpl implements IAccountService {@Autowiredprivate IAccountDao accountDao;public List<Account> findAllAccount() {return accountDao.findAllAccount();}public Account findAccountById(Integer accountId) {return accountDao.findAccountById(accountId);}public void saveAccount(Account account) {accountDao.saveAccount(account);}public void updateAccount(Account account) {accountDao.updateAccount(account);}public void deleteAccount(Integer accountId) {accountDao.deleteAccount(accountId);} }轉載于:https://www.cnblogs.com/zuiren/p/11429727.html
總結
以上是生活随笔為你收集整理的06-基于 XML 和注解 的 IOC 案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 05-常用IOC注解按照作用分类
- 下一篇: 07-XML 文件注解开发