Spring学习笔记(一)

    xiaoxiao2021-12-14  22

    1、Spring

    一个开源的IoC和AOP容器框架。

    IoC,控制反转,依赖对象的创建及维护由应用本身转移到外部容器。

    AOP,面向切面,通过预编译方式和运行期动态代理实现程序功能统一维护的一种技术。

    2、为什么要使用Spring

    (1)降低组件之间的耦合度。

    (2)可以使用容器提供的众多服务,如事务管理服务。

    (3)容器提供单例模式支持。

    (4)容器提供AOP技术。

    (5)容器提供了众多辅助类,能加快应用的开发,如JdbcTemplate。

    (6)Spring对于主流的应用框架提供了集成支持。

    3、实例化Spring容器

    在类路径下寻找配置文件来实例化Spring容器,如下:

    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

    4、实例化Bean

    使用类构造器实例化Bean,如下:

    <bean id="personService" class="com.spring.service.impl.PersonServiceBean" scope="prototype" lazy-init="false" init-method="init" destroy-method="destory"></bean>

    5、实例

    (1)PersonService.java

    public interface PersonService { public void save(); }

    (2)PersonServiceBean.java

    public class PersonServiceBean implements PersonService { public void init(){ System.out.println("初始化"); } public PersonServiceBean(){ System.out.println("我被实例化了"); } public void save(){ System.out.println("执行了PersonServiceBean的save方法"); } public void destory(){ System.out.println("开闭打开的资源"); } }

    (3)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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- scope="singleton",单例模式,(默认)容器只会创建该bean定义的唯一实例。 scope="prototype",原始模型模式,每次从容器获取的bean都是新的实例。 --> <!-- lazy-init="false",立退加载,表示spring启动时,立刻实例化bean。 lazy-init="true",延迟加载,表示spring启动时,不会立刻实例化bean,而是在第一次向容器通过getBean索取bean时才实例化的。 --> <!-- init-method="init",指定初始化bean之后调用的方法。 destroy-method="destory",指定销毁bean之前调用的方法。 --> <bean id="personService" class="com.spring.service.impl.PersonServiceBean" scope="prototype" lazy-init="false" init-method="init" destroy-method="destory"> </bean> </beans>

    (4)Test.java

    public class Test { @org.junit.Test public void test1() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); PersonService personService = (PersonService)ctx.getBean("personService"); personService.save(); } @org.junit.Test public void test2() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); PersonService personService1 = (PersonService)ctx.getBean("personService"); PersonService personService2 = (PersonService)ctx.getBean("personService"); System.out.println(personService1==personService2); } }

    (5)结果

    test1()运行结果:

    我被实例化了 初始化 执行了PersonServiceBean的save方法

    test2()运行结果:

    初始化 我被实例化了 初始化 false
    转载请注明原文地址: https://ju.6miu.com/read-969645.html

    最新回复(0)