spring

本文介绍Spring框架相关内容,提供官网和下载链接,阐述控制反转IOC、面向切面AOP,包括默认对象创建、xml文件合并、自动装配、注解配置等。还提及静态和动态代理,以及使用AOP需导入的包和自定义实现方式。最后说明MyBatis整合Spring的方法和Spring中的事务类型。

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

官网
https://spring.io/projects/spring-framework#learn
下载
https://repo.spring.io/ui/native/release/org/springframework/spring

控制反转IOC,面向切面AOP

默认使用无参构造创建对象

合并多个xml文件,多用于合作开发

自动装配
autowire

注解配置

<?xml version="1.0" encoding="UTF-8"?>

<context:annotation-config/>

使用注解开发,配置文件加上
<context:component-scan base-package=“com.hl…”/>
用来扫描包下的带注解的实体类
实体类加上
@Component
等价于

衍生的注解
dao层 @Repository
service层 @Service
controller层 @Controller

静态代理,AOP底层
动态代理InvocationHandler能自动生成代理类,本质是反射机制
万能动态代理工具
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;

public void setTarget(Object target) {
    this.target = target;
}

//生成得到代理类
public Object getProxy(){
    return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}

//处理代理实例并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object result=method.invoke(target,args);
    return result;
}

}
注意:工具要以接口为对象,一个动态代理可以实现代理多个类,只要它们实现了同一个接口

使用AOP要导入的包

org.aspectj aspectjweaver 1.9.7 runtime

自定义类实现AOP(HelloPointcut 为自定义类)

aop:config
<aop:aspect ref=“hellopoint”>
<aop:pointcut id=“pointcut” expression=“execution(* *(…))”/>
<aop:before method=“after” pointcut-ref=“pointcut”/>
<aop:before method=“before” pointcut-ref=“pointcut”/>
</aop:aspect>
</aop:config>

mybatis整合spring
需要导入mybatis-spring包,

org.mybatis mybatis-spring 2.0.6

官网 http://mybatis.org/spring/zh/index.html
spring要操作数据库需导入spring-jdbc包(版本号最好一样)

org.springframework spring-jdbc 5.3.9

spring中的事务
1、声明式事务

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource"/>
</bean>
<tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>
<aop:config>
    <aop:pointcut id="txPoint" expression="execution(* *.*(..))"/>
    <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="txPoint"/>
</aop:config>

2、编程式事务(要改变原代码,放弃!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值