spring基础入门-综合实践(xml与annotation)

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一样)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

内容概要:本文档主要展示了C语言中关于字符串处理、指针操作以及动态内存分配的相关代码示例。首先介绍了如何实现键值对(“key=value”)字符串的解析,包括去除多余空格和根据键获取对应值的功能,并提供了相应的测试用例。接着演示了从给定字符串中分离出奇偶位置字符的方法,并将结果分别存储到两个不同的缓冲区中。此外,还探讨了常量(const)修饰符在变量和指针中的应用规则,解释了不同类型指针的区别及其使用场景。最后,详细讲解了如何动态分配二维字符数组,并实现了对这类数组的排序释放操作。 适合人群:具有C语言基础的程序员或计算机科学相关专业的学生,尤其是那些希望深入理解字符串处理、指针操作以及动态内存管理机制的学习者。 使用场景及目标:①掌握如何高效地解析键值对字符串并去除其中的空白字符;②学会编写能够正确处理奇偶索引字符的函数;③理解const修饰符的作用范围及其对程序逻辑的影响;④熟悉动态分配二维字符数组的技术,并能对其进行有效的排序和清理。 阅读建议:由于本资源涉及较多底层概念和技术细节,建议读者先复习C语言基础知识,特别是指针和内存管理部分。在学习过程中,可以尝试动手编写类似的代码片段,以便更好地理解和掌握文中所介绍的各种技巧。同时,注意观察代码注释,它们对于理解复杂逻辑非常有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值