05_Spring使用

本文详细介绍Spring框架的整合步骤,包括三层架构设计、XML与注解配置方式、事务管理器配置及AOP切面应用。同时,文章深入探讨如何通过Spring进行CRUD操作,并强调了事务管理的重要性。


#Spring使用

前言

要使用Spring来进行CRUD操作,增删改一定需要**事务管理器**来手动提交事务和回滚事务。查询不需要事务管理器。

在处理预装sql语句中,预处理对象需要多例。例如PreparedStatement

QueryRunner( org.apache.commons.dbutils)都在注入依赖的时候需要添加scope=“prototype”,是因为单程线程不安全,在增删改的时候。

1、通用步骤

###0、pom.xml配置依赖坐标

1、三层架构模式

1、创建实体类(domain包下)
  • 实体类的属性名要与sql的列名相同
  • 生成SetterGetter方法
2、创建持久层接口及实现类(dao和impl包下)
  • 具体执行sql语句的方法
3、创建业务层接口类及实现类(service的impl包和service包下)
  • 设置成员变量为持久层对象
  • 为引用的对象设置Setter方法
private IAccountDao accountDao;
  • 创建执行方法及内容

2、测试(spring整合junit测试)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class JdbcTemplateTest {
    @Autowired
    private IAccountService as;

    @Test
    public void Test(){
      as.transfer("aaa", "bbb", 100f);
    }
}

2、xml配置使用

1、创建配置文件bean.xml

1、引入相关的头部信息及模板
  • 普通的bean标签信息

    <?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">
    	<!-- 将bean加入到Spring容器 -->
        <bean id="..." class="...">
            <!-- 此bean的协作者和配置 -->
        </bean>
        <!-- more bean definitions go here -->
    
    </beans>
    
  • AOP头信息

    <?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"
        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会话作用域的bean,公开为代理 -->
        <bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
        <!-- 指示容器代理周围的bean -->
            <aop:scoped-proxy/>
        </bean>
    
        <!-- 注入了上述bean的代理的单一作用域bean -->
        <bean id="userService" class="com.foo.SimpleUserService">
            <!-- 对 bean的引用 -->
            <property name="userPreferences" ref="userPreferences"/>
        </bean>
    </beans>
    
  • 事务管理器头信息

    <?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: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/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!-- 这个需要注入spring容器的对象 -->
        <bean id="fooService" class="x.y.service.DefaultFooService"/>
    
        <!-- 配置事务管理器,用处在<aop:advisor/> -->
        <tx:advice id="txAdvice" transaction-manager="txManager">
            <!-- 事务语法 -->
            <tx:attributes>
                <!-- 所有的get方法都是制度-->
                <tx:method name="get*" read-only="true"/>
                <!-- 其他的方法使用默认设置,参考下方 -->
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    
        <!-- 确保在执行Service接口定义的任何操作时运行上述事务建议 -->
        <aop:config>
            <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.Service.impl*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
        </aop:config>
    
        <!-- 配置数据源 -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
            <property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/>
            <property name="username" value="scott"/>
            <property name="password" value="tiger"/>
        </bean>
    
        <!-- 同样,配置事务管理器的数据源 -->
        <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <!-- other <bean/> definitions here -->
    
    </beans>
    
  • 注解头部信息 若是有aop,则复制有aop那一行,将aop改为context即可

<?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">

    <context:annotation-config/>

</beans>

2、注入相关的依赖

1、dao(持久层)引用的对象(成员变量有必须有Setter方法)和dao
 <!--配置dataSource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.dao.impl.accountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
2、注入service(业务层)的依赖
 <!--配置service-->
    <bean id="accountService" class="com.service.Impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
3、注入业务层引用的对象(成员变量)依赖
 <!--配置事务管理器-->
    <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManger">
        <tx:attributes>
            <!--配置事务属性
                isolation:指定事务的隔离级别。默认值是default,表示使用数据库的隔离剂级别
                propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择,查询的方法可以选择SUPPORTS
                read-only:用于指定事务是否为只读,只有查询方法才能设置为true。默认值为false,表示读写
                timeout:用于指定事务的超时时间,默认值为-1,表示永不超时。如果指定了数值,以秒为单位
                rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚。
                no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,表示任何异常都回滚。
                -->
            <tx:method name="transfer" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" read-only="true" propagation="SUPPORTS"></tx:method>
        </tx:attributes>
    </tx:advice>

3.1、或者配置切面(事务通知)
 <!--配置Aop-->
    <aop:config>
        <aop:pointcut id="pt" expression="execution(* com.service.Impl.*.*(..))"/>
        <aop:aspect id="txAdvice" ref="transManger">
            <aop:before method="beginTransaction" pointcut-ref="pt"/>
            <aop:after-returning method="commit" pointcut-ref="pt"/>
            <aop:after-throwing method="rollback" pointcut-ref="pt"/>
            <aop:after method="release" pointcut-ref="pt"/>
        </aop:aspect>
    </aop:config>

3、XML+注解配置


1、注入相关依赖(类、成员变量)

2、配置bean

1、扫描包
<!--配置容器时要扫描包-->
    <context:component-scan base-package="com"></context:component-scan>

2、配置jar
 <!--配置JDBCTemplate-->
    <bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置dataSource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
	<!--
    spring基于注解的声明式事务控制配置步骤
        1、配置事务管理器
        2、开启spring对注解事务的支持
        3、在需要事务支持的地方使用注解@Transactional
    -->

    <!--配置事务管理器-->
    <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
3、开启spring对注解AOP/事务的支持
<!-- 启用spring对AspectJ注解的支持 -->
    <aop:aspectj-autoproxy/>

 <!-- 开启spring对注解事务的支持 -->
    <tx:annotation-driven transaction-manager="transactionManger"/>

4、纯注解


1、创建一个配置包(config)

1、创建一个主配置类(springConfiguration)
/**
  *spring配置类,相当于bean.xml
 **/
@Configuration//标记为主配置
@ComponentScan("com")//扫描包
@Import({jdbcConfig.class, transactionConfig.class})//引入配置类
@PropertySource("classpath:jdbcConfig.properties")//配置文件源
@EnableTransactionManagement//开启事务支持
public class SpringConfiguration {
}
2、创建一个配置文件,用来连接数据库(jdbcConfig.properties)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring
jdbc.username=root
jdbc.password=123456
4、创建一个连接数据库的类(jdbcConfig)
public class jdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource ds) {
        return new JdbcTemplate(ds);
    }

    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        System.out.println(driver+url+username+password);
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}
5、 和事务相关的配置类(或者是其他)
public class transactionConfig {
    /**
     * 用于创建事务管理对象
     * @param ds
     * @return
     */
    @Bean(name = "transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource ds){
        return new DataSourceTransactionManager(ds);
    }
}

2、将类加入spring容器,并且注入相关的依赖

@Repository("accountDao")//加入spring容器
public class accountDaoImpl  implements IAccountDao {

    @Autowired//注入依赖
    private JdbcTemplate jt;

@Service("accountService")
@Transactional(readOnly = true, propagation= Propagation.SUPPORTS)//定义事务类
public class AccountService implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

,并且注入相关的依赖

@Repository("accountDao")//加入spring容器
public class accountDaoImpl  implements IAccountDao {

    @Autowired//注入依赖
    private JdbcTemplate jt;

@Service("accountService")
@Transactional(readOnly = true, propagation= Propagation.SUPPORTS)//定义事务类
public class AccountService implements IAccountService {

    @Autowired
    private IAccountDao accountDao;
Allen_Spring 是一个与汽车电子控制系统通信相关的术语,可能与 CAN(Controller Area Network)总线技术有关。PCAN(PC CAN)工具是由德国公司 PEAK-System 提供的一系列硬件和软件解决方案,用于 CAN 总线的开发、测试和分析。如果 Allen_Spring 与 PCAN 工具有关,它可能涉及特定的应用场景或配置。 以下是一些与 PCAN 工具和 CAN 总线技术相关的文档和资源,可能对查找 Allen_Spring 相关信息有所帮助: ### PCAN 工具的技术文档和使用指南 1. **PCAN-View 用户手册** PCAN-View 是一个用于 CAN 总线通信的免费软件工具,支持数据监控、发送和接收功能。用户手册详细介绍了如何配置和使用该软件,包括 CAN 通道设置、过滤器配置和日志记录功能[^1]。 2. **PCAN-Basic API 文档** 如果 Allen_Spring 涉及软件开发,PCAN-Basic 是一个用于 Windows 和 Linux 平台的编程接口,允许开发者通过 C/C++、C# 或 Python 与 CAN 设备通信。API 文档提供了函数列表、参数说明和示例代码[^2]。 3. **PCAN-Explorer 5 使用指南** PCAN-Explorer 5 是一个功能强大的 CAN 分析工具,支持 DBC 文件解析、信号解码和自动化脚本编写。使用指南中包含了如何导入 DBC 文件、配置 CAN 通道以及编写简单的自动化测试脚本[^3]。 4. **PCAN-USB 硬件手册** 如果 Allen_Spring 涉及硬件设备,PCAN-USB 是一种常见的 CAN 接口设备。硬件手册详细说明了设备的物理接口、驱动安装步骤以及如何通过 USB 连接 CAN 总线网络[^4]。 5. **CANoe 和 PCAN 的集成** 在某些应用场景中,Allen_Spring 可能与 CANoe(Vector 公司的 CAN 总线仿真和测试工具)相关。PCAN 设备可以通过 CANoe 进行集成,用于复杂的 CAN 网络仿真和测试。相关的技术文档包括 CANoe 的用户手册和 PCAN 插件的安装指南[^5]。 ### 示例代码:使用 PCAN-Basic API 发送 CAN 消息 以下是一个使用 PCAN-Basic API 发送 CAN 消息的简单 Python 示例代码: ```python from pcan_basic import * # 初始化 PCAN 设备 result = CAN_Initialize(PCAN_USB, BAUD_500K, 2, 60, 0) if result != PCAN_ERROR_OK: print("Failed to initialize PCAN device") exit() # 准备 CAN 消息 msg = TPCANMsg() msg.ID = 0x100 msg.MSGTYPE = PCAN_MESSAGE_STANDARD msg.LEN = 8 msg.DATA = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08] # 发送 CAN 消息 result = CAN_Write(PCAN_USB, msg) if result != PCAN_ERROR_OK: print("Failed to send CAN message") else: print("CAN message sent successfully") # 关闭 PCAN 设备 CAN_Uninitialize(PCAN_USB) ``` ### 相关问题 1. 如何在 Python 中使用 PCAN-Basic API 进行 CAN 总线通信? 2. PCAN-Explorer 5 支持哪些 DBC 文件格式? 3. 如何在 Linux 系统中安装和配置 PCAN-USB 驱动? 4. CANoe 如何与 PCAN 设备集成进行 CAN 总线仿真? 5. 如何使用 PCAN-View 进行 CAN 总线日志记录和分析? 如果 Allen_Spring 是特定的项目名称或公司内部工具,建议联系相关技术支持或查阅内部文档以获取更详细的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值