spring基础入门-综合实践(xml与annotation)
项目目录结构
建立一个普通的动态web项目,并导入所需的jar包,编写文件
IAccountDao.java
package com.zh.dao;
import com.zh.entity.Account;
public interface IAccountDao {
/**
* 更新账户
* @param account 账户
*/
public abstract void updateAccount(Account account);
/**
* 查找账户
* @param name 姓名
* @return 返回账户
*/
public abstract Account findAccount(String name);
}
AccountDaoImpl.java
package com.zh.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.zh.dao.IAccountDao;
import com.zh.entity.Account;
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account findAccount(String name) {
List<Account> account = jdbcTemplate.query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class),name);
if(account.isEmpty()) return null;
if(account.size()>1)throw new RuntimeException("结果集不唯一");
return account.isEmpty() ? null : account.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=? ,money=? where id=?", account.getName(),account.getMoney(),account.getId());
}
}
Account.java
package com.zh.entity;
public class Account {
//账户id
private Integer id;
//姓名
private String name;
//账户上的钱
private float money;
public Account() {
super();
// TODO Auto-generated constructor stub
}
public Account(Integer id, String name, float money) {
super();
this.id = id;
this.name = name;
this.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;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
IAccountService.java
package com.zh.service;
import com.zh.entity.Account;
public interface IAccountService {
/**
* 根据名字查询账户
* @param name 姓名
* @return 账户
*/
public Account findAccount(String name);
/**
* 模拟转账
* @param sourceName 被转账账户(源)
* @param targetName 转账账户(目)
* @param money 转账数目
*/
public void accountTransfer(String sourceName, String targetName, float money);
}
AccountServiceImpl.java
package com.zh.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zh.dao.IAccountDao;
import com.zh.entity.Account;
import com.zh.service.IAccountService;
@Service("accountService")
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccount(String name) {
Account account = accountDao.findAccount(name);
return account;
}
@Override
public void accountTransfer(String sourceName, String targetName, float money) {
Account source = accountDao.findAccount(sourceName);
Account target = accountDao.findAccount(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDao.updateAccount(source);
//模拟出现异常,检验事务是否被控制住(rollback)
//int i = 1/0;
accountDao.updateAccount(target);
}
}
Test.java
package com.zh.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zh.service.IAccountService;
public class Test {
public static void main(String[] args) {
/**
* 加载spring核心配置文件
*/
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:beans.xml");
/**
* 获取AccountServiceImpl对象
* 使用接口接收,否则报异常
*/
IAccountService accountService = ac.getBean("accountService",IAccountService.class);
//查看账户
System.out.println(accountService.findAccount("zh"));
System.out.println(accountService.findAccount("lisi"));
//转账操作
accountService.accountTransfer("zh", "lisi", 220f);
}
}
beans.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="com.zh" />
<!-- 配置 JdbcTemplate并注入DataSource-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 加载db.properties文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置 DataSource并注入-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置spring开启注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 在需要事务的地方使用@Transactional
该注解可以写在接口、类和方法上
写在接口上,表示该接口的所有实现类都有事务
写在类上,表示该类的所有方法有事务
写在方法上,表示该方法有事务
优先级:就近原则
-->
</beans>
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.user=root
jdbc.password=root
运行Test.java效果(跟基于xml一样)