【Java】Spring5学习笔记

本文深入介绍了Spring框架的核心特性,包括IOC(控制反转)、DI(依赖注入)的实现方式,如构造器注入和属性注入,以及自动装配的原理。此外,讲解了AOP(面向切面编程)的三种实现方式,和Mybatis的Spring整合。还涵盖了声明式事务管理,以及Spring中不同作用域的概念。通过对XML配置和注解方式的比较,展示了Spring的灵活性和实用性。

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

官方文档
详细笔记1
详细笔记2 微信

2. IOC 控制反转

所谓的Ioc,一句话搞定:对象由Spring来创建,管理,装配
只需要修改xml,不需要改程序

  1. bean里注册的类使用的构造方法,默认使用无参构造
  2. 有参构造(spring 文档1.4.1):,也称构造器注入
    1. 通过下标
    2. 通过指定类型
    3. 参数名

property 设置属性 即类内的set方法使用
constructor-arg 构造使用
 <bean id="user" class="com.liang.pojo.User">
     <constructor-arg name="name" value="亮亮"/>
     <property name="age" value="3"/>
 </bean>

总结:在配置文件加载的过程中,对象就全部被创建了

5.Spring配置

别名

<alias name="user" alias="userAlias"/>
或者直接在创建时指定name,且可多个 u2也是
<bean id="user" class="com.liang.pojo.User" name="userAlias,u2">
    <constructor-arg name="name" value="亮亮"/>
    <property name="age" value="3"/>
</bean>

导入

<import resource="beans.xml"/>

6.依赖注入

set方式

  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象中的所有属性,由容器来注入

多种类型注入方式

<bean id="address" class="com.liang.pojo.Address">
    <property name="address" value="长沙"/>
</bean>

<bean id="student" class="com.liang.pojo.Student" name="studentAlias">
    <!--普通-->
    <property name="name" value="liang"/>
    <!--引用类型-->
    <property name="address" ref="address"/>
    <!--数组-->
    <property name="books">
        <array>
            <value>英语</value>
            <value>数学</value>
        </array>
    </property>
    <!--List-->
    <property name="hobbies">
        <list>
            <value>看电视</value>
            <value>上网</value>
        </list>
    </property>
    <!--map-->
    <property name="card">
        <map>
            <entry key="身份证" value="1234656"/>
            <entry key="学生证" value="125445"/>
        </map>
    </property>

    <!--null-->
    <property name="wife">
        <null/>
    </property>

    <!--properties-->
    <property name="info">
        <props>
            <prop key="性别"></prop>
            <prop key="电话">123435</prop>
        </props>
    </property>
</bean>

扩展注入方式

p命名和c命名空间

beans属性中加上
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:c="http://www.springframework.org/schema/c"
	
	p相当于直接set c相当于构造注入
    <bean id="user" class="com.liang.pojo.User" c:name="" p:age="24"/>

作用域

默认为单例, 即只有一个对象

<bean id="user" class="com.liang.pojo.User" c:name="" p:age="24" scope="singleton"/>

原型模式, get一次就创建一个新的

<bean id="user" class="com.liang.pojo.User" c:name="" p:age="24" scope="prototype"/>

7.自动装配

autowire
byName
byType

<bean id="cat" class="com.liang.pojo.Cat"/>
<bean id="dog" class="com.liang.pojo.Dog"/>

<bean id="people" class="com.liang.pojo.People" autowire="byName"/>

使用注解自动装配

java pojo 实体类的属性前加注解,(可不定义set方法)

@Autowired
private Cat cat;
@Autowired
private Dog dog;

beans的xml定义如下 要定义好同类型的对象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"
       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
       https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <bean id="cat" class="com.liang.pojo.Cat"/>
    <bean id="dog" class="com.liang.pojo.Dog"/>
    <bean id="dog" class="com.liang.pojo.Dog"/>
    <bean id="people" class="com.liang.pojo.People"/>
</beans>

PS:@Autowired优先使用byType的方式进行加载,若容器内多个同类型的对象,则根据ByName确定

如果情况复杂,可使用指定装配对象的id名
如下 指定装配dog22的

@Autowired
@Qualifier("dog22")
private Dog dog;
<bean id="cat" class="com.liang.pojo.Cat"/>
<bean id="dog22" class="com.liang.pojo.Dog"/>
<bean id="dog" class="com.liang.pojo.Dog"/>
<bean id="people" class="com.liang.pojo.People"/>

还有@Resource注解可以做到Autowired的功能, 但一般使用@Autowired即可

@Resource(name="dog22")
private Dog dog;

小结:
@Autowired用byType方式查找
@Resource 用byName方式

8.使用注解开发

@Autowired
@Resource
@Component 自动创建
@Value(“liang”) 注入值 使用

@Component
public class User {
    @Value("liang")
    public String name;
}
<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="com.liang.pojo"/>
    
</beans>

@Component 衍生的注解

  • dao @Repository
  • service @Service
  • controller @Controller
    这四个注解功能都是一样的,都代表将某个类注册到Spring中,装配Bean

小结
xml更加万能
注解维护困难

xml和注解的最佳实践

  • xml用来管理bean
  • 注解只负责完成属性的注入

9.使用java的方式配置Spring

JavaConfig

配置类

// 这个也会Spring容器托管,注册到容器中,因为@Configuration他本来就是个@Component
// @@Configuration代表这是一个配置类,就和我们之前看的beans.xml一样
@Configuration
@ComponentScan("com.liang.pojo")	//自动扫描pojo包里带@Component的组件
//@Import()
public class LiangConfig {
    //注册一个bean 就相当于我们之前写的一个bean标签
    // 这个方法的名字就相当于bean标签中的id属性
    // 这个方法的返回值就相当于bean标签中的class属性
    @Bean
    public User getUser() {
        return new User();
    }
}

实体类

@Component
public class User {
    private String name;
    public User() {
        System.out.println("User创建");
        name = "a";
    }
    public String getName() {
        return name;
    }
//    @Value("liang")
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
public void test1(){
    ApplicationContext context = new AnnotationConfigApplicationContext(LiangConfig.class);
    User getUser = (User) context.getBean("getUser");
    System.out.println(getUser.hashCode());
}

分析:这样其实User会创建两次 一次是配置文件启动时扫描到实体类的bean,第二次是调用(User) context.getBean(“getUser”);

10.代理模式

静态代理

代码步骤
1. 接口
2. 真实角色
3. 代理角色
4. 客户端访问代理角色

代理模式的好处:

  • 可以使真实角色的操作更加纯粹 不用去关注一些公共的业务
  • 公共也就交给代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
    缺点
  • 一个真实角色就会产生一个代理角色,代码量会翻倍,开发效率变低

动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口==JDK动态代理
    • 基于类:cglib
    • java字节码 JAVAssist

代理有关类与代码

//等会我们会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
    private Object target;

    public Object getRent() {
        return target;
    }

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

    public void logInfo(String msg) {
        System.out.println("执行了"+msg+"方法");
    }
    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        logInfo(method.getName());
        //动态代理的本质,就是使用反射机制实现
        Object result = method.invoke(target, args);
        return result;
    }
}

主程序

    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理角色 现在没有
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象
        pih.setRent(host);
        Rent proxy = (Rent) pih.getProxy();
        proxy.rent();
        proxy.sale();
    }

真实类与接口

public interface Rent {
    public void rent();
    public void sale();
}
public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
    @Override
    public void sale() {
        System.out.println("房东要卖房");
    }
}

小结:
Proxy.newProxyInstance(…) 生成代理实例 其中的参数含要代理的目标类的接口(Rent)以及InvocationHandler生成的对象
InvocationHandler提供了invoke方法,代理调用的时候先走这个万能方法,方法内再调用真正目标的方法

11.AOP

面向切面编程

方式一:使用Spring的API接口

log

public class BeforeLog implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + "类的"+method.getName()+"被执行了");
    }
}

public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(method.getName()+"返回了"+returnValue);
    }
}
<?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">

<!--    注册bean-->
    <bean id="afterLog" class="com.liang.log.AfterLog"/>
    <bean id="beforeLog" class="com.liang.log.BeforeLog"/>
    <bean id="userServiceImpl" class="com.liang.service.UserServiceImpl"/>
<!--    方式一:使用原生Spring API接口-->
<!--    配置aop-->
    <aop:config>
<!--        切入点:expression表达式, execution(要执行的位置 )-->
        <aop:pointcut id="pointcut" expression="execution(* com.liang.service.UserServiceImpl.*(..))"/>
<!--        执行环绕增加-->
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

方法二:使用自定义类(切面)

切入

public class diyPointCut {
    public void before(){
        System.out.println("======方法执行前=======");
    }
    public void after(){
        System.out.println("======方法执行后=======");
    }
}

xml中加以下

    <!--方式二 自定义类-->
    <bean id="diy" class="com.liang.diy.diyPointCut"/>
    <aop:config>
        <!--自定义切片 ref要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="pointcut" expression="execution(* com.liang.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解实现

@Aspect  //标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.liang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("======方法执行前=======");
    }
    @After("execution(* com.liang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("======方法执行后=======");
    }
    @Around("execution(* com.liang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        Signature signature = jp.getSignature();
        System.out.println("signature:"+signature);
        Object proceed = jp.proceed();
        System.out.println("环绕后");
    }
}
    <bean id="diy" class="com.liang.diy.AnnotationPointCut"/>
    <aop:aspectj-autoproxy/>

12. 整合Mybatis

12.1回忆Mybatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试

Spring-Mybatis

方式一

  1. 编写数据源配置
  2. sqlSessionFactory
  3. sqlSessionTemplate
  4. 需要给接口加实现类
  5. 注册实现类,并注入sqlSession
  6. 测试

前三个配置及注册
spring-dao.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!--数据源配置-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>   
    <!--sqlSessionFactory配置-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
<!--        绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/liang/mapper/*.xml"/>
    </bean>
    <!--SqlSessionTemplate 就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userMapper" class="com.liang.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

对应的实现类

public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

测试

    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }

方式二

  1. 编写数据源配置
  2. sqlSessionFactory
  3. 编写实现了Mapper接口并继承了的类
  4. 注册实现类并注入sqlSessionFactory
  5. 测试

留下数据源配置和sqlSessionFactory,注册实现类

    <bean id="userMapper2" class="com.liang.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

实现类及测试

实现类
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

测试方法
    @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper2 = context.getBean("userMapper2", UserMapper.class);
        List<User> users = userMapper2.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

13. 声明式事务

1. 回顾事务

  • 把一组业务当成一个业务来做;要么都成功,要么都失败
  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题
  • 确保完整性和一致性

事务ACID原则

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能操作统一资源,防止数据损坏
  • 持久性
  • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化写到存储器中

1.Spring事务

  1. 编程式事务
  2. 声明式事务

spring声明式事务步骤

  1. 配置声明式事务
  2. 结合AOP实现事物的织入,配置事务通知
  3. 配置事务切入

只需要在已有配置文件中 添加以下配置即可完成

    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
    <!--结合AOP实现事物的织入
    配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.liang.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值