xml的ioc案例
1.环境搭建pom.xml
<packaging>jar</packaging>
<dependencies>
<!--spring坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--封装了JDBC的代码,简化dao层的操作-->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!--c3p0连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2.创建sql
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);
3.创建domain.Account实体类
/**
* 账户实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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;
}
}
4.创建IAccountService, AccountServiceImpl
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findById(Integer accountId);
/**
* 保存操作
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
*删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findById(Integer accountId) {
return accountDao.findById(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);
}
5创建.IAccountDao accountDaoImpl
/**
* 账户持久层接口
*/
public interface IAccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findById(Integer accountId);
/**
* 保存操作
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
*删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
/**
* 账户持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
//封装了JDBC的代码,简化dao层的操作
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try {
return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
}catch (Exception e){
throw new RuntimeException(e);
}
}
public Account findById(Integer accountId) {
try {
return runner.query("select * from account 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 account(name,money) values(?,?)", account.getName(),account.getMoney());
}catch (Exception e){
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update("update account set name = ?, money = ? where id = ?", account.getName(),account.getMoney(),account.getId());
}catch (Exception e){
throw new RuntimeException(e);
}
}
6.搭建spring的开发环境
在resource下创建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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置service对象-->
<bean id="accountService" class="sise.cn.service.Impl.AccountServiceImpl">
<!--注入dao set方法注入 其他bean类型注入-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao对象-->
<bean id="accountDao" class="sise.cn.dao.Impl.AccountDaoImpl">
<!--注入QueryRunner set方式注入 其他bean类型注入 -->
<property name="runner" ref="runner"></property>
</bean>
<!--配置QueryRunner对象 单例对象,可能这个用完其他在用会造成线程安全问题 所以要配scope="prototype",保证每次使用这个对象时都是创建一个新的-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源 构造函数注入 其他bean类型注入-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源c3p0-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--注入连接数据库的必备信息 set方法注入 基本类型和String注入-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc://mysql://localhost:3306/eesyioc"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
7.test:使用junit测试 (并不关注)
/**
* s使用junit单元测试:测试配置
*/
public class AccountServiceTest {
@Test
public void testFindAll() {
//1.获取容器对象
ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = cs.getBean("accountService",IAccountService.class);
//3.执行方法
List<Account> accounts = as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testFindOne() {
//1.获取容器对象
ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = cs.getBean("accountService",IAccountService.class);
//3.执行方法
Account account = as.findById(1);
System.out.println(account);
}
@Test
public void testSave() {
Account account = new Account();
account.setMoney(12345f);
account.setName("6ms");
//1.获取容器对象
ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = cs.getBean("accountService",IAccountService.class);
//3.执行方法
as.saveAccount(account);
}
@Test
public void testUpdate() {
//1.获取容器对象
ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = cs.getBean("accountService",IAccountService.class);
//3.执行方法
Account account = as.findById(4);
account.setMoney(23456f);
as.updateAccount(account);
}
@Test
public void testDelete() {
//1.获取容器对象
ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = cs.getBean("accountService",IAccountService.class);
//3.执行方法
as.deleteAccount(4);
}
}
要点:
1.能不能看出来QueryRunner也需要注入
2.注入QueryRunner时数据源dataSource也可以实现配置并且把连接数据库的信息注入进来
3.能不能看出来QueryRunner如果是单例对象,面临多个dao使用时会产生线程安全问题
注解ioc案例
在xml的基础上改进
1.导入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/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="sise.cn"></context:component-scan>
<!--配置QueryRunner对象 单例对象,可能这个用完其他在用会造成线程问题 所以要配scope="prototype",保证每次使用这个对象时都是创建一个新的-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源 构造函数注入 其他bean类型注入-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源c3p0-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--注入连接数据库的必备信息 set方法注入 基本类型和String注入-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesyioc"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
2.在AccountServiceImpl里实现把其加入spring容器中的注解
/**
/**
* 账户的业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired//当用注解实现自动注入时set方法就不是必须的了
private IAccountDao accountDao;
3.AccountDaoImpl
/**
* 账户持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
//封装了JDBC的代码,简化dao层的操作
@Autowired//当用注解实现自动注入时set方法就不是必须的了
private QueryRunner runner;