- Spring准备学习
- spring的三个层次
- 核心、组件和应用
- IOC容器和AOP模块是Spring的核心
- spring的设计理念
- 面向接口开发而不依赖于具体的产品实现
- IOC容器
控制反转也叫依赖注入。对象的创建、初始化、销毁等。利用了工厂模式
将对象交给容器管理,你只要在spring配置文件中配置相应的bean,以及相关属性。让spring容器来生成累的实例以及管理对象。减少类之间的相互依赖,解耦合。
IOC容器是spring实现依赖控制反转的载体。可以在对象生成或者初始化时直接将数据注入到对象,简化对象依赖关系的管理,也简化了面向对象系统的复杂性。
一般的java设计,对象与对象之间的依赖关系通过new关键字来创建模式是:对象–对象。现在IOC是一个统一的对象实例管理,模式是:对象–IOC容器–对象。
先把实例注入到IOC容器中,让容器主动管理其中的依赖关系,具体的注入方式包括 接口注入、构造器注入、setter注入。
- IOC容器核心
创建一个spring-context/src/test/java/com/lzl/test/HelloWorld.java的JavaBean
public class HelloWorld { public HelloWorld(){ System.out.println("==构造方法=="); } public void init(){ System.out.println("==init=="); } public void sayHello(){ System.out.println("hello Spring!"); } public void destroy(){ System.out.println("==destroy=="); } }
创建一个/spring-context/src/test/resources/org/springframework/jmx/helloWorld.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <!-- 默认情况下,spring创建对象是单例模式。 可以通过设置scope来设置对象的模式 singleton 单例模式 prototype 多例 --> <beans> <!-- init-method 有spring容器调用 在构造方法执行之后开始执行。 destroy-method 如果bean是単例,则有spring来进行关闭和销毁 如果bean是多例,则speing容器不负责销毁 说明: 如果该bean是単例,由spring来管理其生命周期 如果该bean是多例,spring的资源由程序来关闭 --> <bean id="helloWorld" class="com.lzl.test.HelloWorld" scope="singleton" init-method="init" destroy-method="destroy"></bean> </beans>
建立测试类/spring-context/src/test/java/com/lzl/test/ClassPathXmlApplicationTest.java
public class ClassPathXmlApplicationTest { /** * 该方法主要是验证资源文件是如何加载的? */ public static String path="org/springframework/jmx/helloWorld.xml"; public static ApplicationContext fileResource; static{ //初始化IOC容器 fileResource = new ClassPathXmlApplicationContext(path); } @Test public void refreshSourceTest(){ //创建对象 HelloWorld h = (HelloWorld) fileResource.getBean("helloWorld"); h.sayHello(); HelloWorld h2 = (HelloWorld) fileResource.getBean("helloWorld"); h.sayHello(); System.out.println(h.toString()); System.out.println(h2.toString()); } @Test public void testInitDestroy(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(path); HelloWorld h = (HelloWorld) context.getBean("helloWorld"); h.sayHello(); context.close(); } }
总结
spring的IOC容器代替了类的创建的工程。他是通过spring提供的一些ApplicationContext的方法进行对象的实例化,并且来管理类的。