Spring中使用事务搭建转账环境方法二 相对简便的注解方法 ——配置文件注入对象属性需要setter方法 注解方法,不需要生成setter方法

本文介绍如何使用Spring框架进行事务管理和AOP操作。通过XML配置文件详细展示了配置事务管理器、开启事务注解、定义DAO和服务层,并实现转账业务逻辑的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"
    xmlns:aop="http://www.springframework.org/schema/aop" 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/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- c3p0连接池得到dataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sw_database"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="accountDao" class="com.swift.AccountDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <bean id="accountService" class="com.swift.AccountService">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

</beans>

事务的注解方法依然需要事务管理器DataSourceTransactionManager,这个管理器当然需要数据源DataSource来确认指向哪个数据库,即注入dataSource。

然后开启事务注解的扫描<tx:annotation-driven transaction-manager="transactionManager"/>

程序中在需要增强的类上用@Transactional标记就可以了,自动调用对该类所有方法进行增强的事务,不用再像前边的配置文件方法,自己定义

省去了下面步骤

<!--  配置事务增强 -->
    <tx:advice id="txadvice" transaction-manager="transactionManager">
        <!-- 做事务操作 -->
        <tx:attributes>
            <!-- 事务操作的方法匹配规则 -->
            <tx:method name="money*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

也省去了切入点、切面的aop操作

<!-- 配置切面 -->
    <aop:config>
    <!-- 切入点 -->
    <aop:pointcut expression="execution(* com.swift.AccountService.*(..))" id="pointcut1"/>
    <!-- 切面 -->
    <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/>
    </aop:config>

 

其他的类dao类和Service类没有改变

代码如下:

package com.swift;

import org.springframework.jdbc.core.JdbcTemplate;

public class AccountDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //少钱的方法
    public void lessMoney(String from,double number) {
        String sql="update account set money=money-? where username=?";
        jdbcTemplate.update(sql, number,from);
        
    }
    //多钱的方法
    public void moreMoney(String to,double number) {
        String sql="update account set money=money+? where username=?";
        jdbcTemplate.update(sql, number,to);
    }
}

Service类

package com.swift;

import org.springframework.transaction.annotation.Transactional;

@Transactional 
public class AccountService {
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    
    public void moneyTransfer(String from,String to,double number) {
        accountDao.lessMoney(from,number);
        int i=10/0;
        accountDao.moreMoney(to,number);
    }
}

配置文件注入对象属性需要setter方法 注解方法,不需要生成setter方法

下边是注解方法注入属性

package com.swift;

import javax.annotation.Resource;

public class Service {
    @Resource(name="studentDao")
    private StudentDao studentDao;
    @Resource(name="courseDao")
    private CourseDao courseDao;
    public String fun() {
        return "This is Service's fun()........."+this.studentDao.fun()+this.courseDao.fun();
    }
}

aop操作复习

    <bean id="book" class="com.swift.aop.Book"></bean>
    <bean id="adviceBook" class="com.swift.aop.AdviceBook"></bean>
    
    <aop:config>
    <!-- 切入点表达式第一个*表示public private等权限后接空格,第二个*表示任意方法(..)表示参数 -->
    <aop:pointcut expression="execution(* com.swift.aop.Book.*())" id="pointcut1"/>
    
    <!-- 哪个切面(用来增强切入点的类) 名称是什么用ref表示 -->
    <aop:aspect ref="adviceBook">
    <!-- 增强的具体方法,增强哪个切入点 -->
    <aop:before method="before" pointcut-ref="pointcut1"/>
    </aop:aspect>
    </aop:config>

只要调用book对象中的任意方法就可以得到增强后的效果

 

<think>好的,我现在需要帮助用户了解Java中常用的注解及其用法。首先,我要回想一下用户提供的参考引用内容,确保回答准确。用户提到了四个引用,涉及注解的基本概念、常用注解、解析方法以及事务管理相关的注解。 首先,我应该从基础开始,解释什么是Java注解,引用[1]提到注解是元数据,影响代码执行,但有些可以影响,比如@Override。然后,按照用户的要求,列出常用注解,并分类说明。比如内置注解如@Override、@Deprecated,元注解如@Target、@Retention,框架注解Spring的@Autowired、@Service,以及事务相关的@Transactional(引用[4]提到在service层使用)。 接下来,需要详细每个注解的作用和使用场景。例如,@Override用于方法重写,@Deprecated标记过时方法,@SuppressWarnings抑制警告。元注解部分,要解释@Target指定使用位置,@Retention定义保留策略,@Documented包含在Javadoc中,@Inherited是否被子类继承。 框架相关的注解部分,Spring的@Autowired自动装配,@Component及其派生注解如@Service、@Repository,@RequestMapping处理请求映射。事务管理中的@Transactional需要说明其位置和作用,如开启事务、提交或回滚(引用[4])。 然后,如何解析注解?引用[3]提到通过反射获取类、方法、变量上的注解对象,并获取属性值。这部分可以简要说明,比如使用Class.getAnnotations()等方法。 最后,生成相关问题,覆盖用户可能感兴趣的扩展内容,如注解原理、自定义注解Spring注解对比、替代XML配置、处理重复注解等。确保问题有逻辑性,帮助用户深入学习。 需要检查所有注解的例子是否正确,比如@Override是否正确使用,是否有遗漏的重要注解,比如Lombok的@Getter/@Setter是否值得提及?但用户提供的引用中没有提到Lombok,可能用户更关注标准注解Spring相关,所以暂加入。 确保每个部分都有对应的引用标记,比如在事务管理部分加上[^4],解析注解部分引用[^3]。同时,保持回答结构清晰,分点列出,便于阅读。</think>### Java常用注解列表及作用解析 #### 一、Java注解基础概念 Java注解(Annotation)是为代码提供元数据的标记,直接影响代码逻辑,但可通过编译检查或反射机制间接影响程序行为[^1]。例如: ```java @Override // 标记方法为重写父类方法 public String toString() { return "注解示例"; } ``` #### 、常用内置注解 1. **@Override** - **作用**:标识方法重写父类/接口的方法 - **场景**:编译时检查方法签名是否正确 ```java @Override public void show() { System.out.println("子类实现"); } ``` 2. **@Deprecated** - **作用**:标记类、方法或字段已过时 - **场景**:配合@since和@forRemoval实现版本过渡 ```java @Deprecated(since = "Java 9", forRemoval = true) public void oldMethod() {} ``` 3. **@SuppressWarnings** - **作用**:抑制编译器警告(如未使用变量) - **参数**:`"unchecked"`、`"deprecation"`等 ```java @SuppressWarnings("unchecked") List list = new ArrayList(); ``` #### 三、元注解(定义注解注解) 1. **@Target** - **作用**:指定注解使用位置 - **取值**:`ElementType.METHOD`(方法)、`TYPE`(类)等 ```java @Target(ElementType.METHOD) public @interface Loggable {} ``` 2. **@Retention** - **作用**:定义注解保留策略 - **策略**: - `SOURCE`:仅源码可见(如@Override) - `CLASS`:编译后保留但JVM加载 - `RUNTIME`:运行时可通过反射获取[^3] ```java @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation {} ``` #### 四、框架常用注解 1. **Spring框架注解** - **@Autowired**:自动注入依赖对象 - **@Service/@Repository**:标记业务层/持久层组件 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; } ``` 2. **事务管理注解** - **@Transactional**:声明方法需要事务管理(提交/回滚) ```java @Transactional(rollbackFor = Exception.class) public void transferMoney() { /* 转账逻辑 */ } ``` 3. **Web请求处理** - **@RequestMapping**:映射HTTP请求到控制器方法 ```java @RestController public class UserController { @GetMapping("/users") public List<User> listUsers() { /* ... */ } } ``` #### 五、注解解析方法 通过反射API获取注解信息: ```java Class<?> clazz = MyClass.class; if (clazz.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation anno = clazz.getAnnotation(MyAnnotation.class); System.out.println(anno.value()); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值