04-spring-控制反转

使用myeclipse开发spring一个Demo。

第一步:新建一个web project。

第二步:安装spring开发的支持包。

安装后多了这几个东西

 3,定义一个操作接口:

package com.Spring.Demo;

public interface IFruit {
    
    public void eat();

}

4,定义接口操作子类。

 package com.Spring.Demo;

public class Apple implements IFruit {

    @Override
    public void eat() {

        System.out.println("吃苹果");
    }
    
}

随后不提供有工厂的操作类,因为spring本身就有工厂类。在之后的工作就不应该出现工厂类。

5,修改applicationContext.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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

    <bean id="apple" class="com.Spring.Demo.Apple"></bean>

</beans>

6,随后通过特定模式启动spring容器。

找到子类操作接口。

package com.Spring.Demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestApple {

    public static void main(String[] args) {

        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        IFruit fruit=ctx.getBean("apple",Apple.class);
        fruit.eat();
    }
}

整个代码操作过程中无法发现工厂设计模式的明确使用,因为所有的工厂都由spring帮助用户处理了。而且在

applicationContext.XML配置文件里,都在spring容器启动时候默认实例化好了所有的对象。

使用的时候,根据ID名称取出即可。

使用过程中的类:

1,应用上下文类:ApplicationContext

 所有配置的信息都需要通过此类读取。

常用方法:getBean(String name,Class<T> requireType)。取得指定名称的bean对象,并且设置泛型为指定操作的bean类型,避免向下转型

2,由于资源控制文件可能在任意位置上,例如CLASSPATH或者磁盘中,那么必须使用相关子类:

 ClassPathXmlApplicationContext("ClassPath");表示在CLASSPATH中读取资源文件。

所有spring配置的<bean>元素都表示在spring容器启动的时候自动初始化,所以在使用对象之前已经准备好了供用户使用的实例,

用户在使用的时候,只需要通过bean的ID,获取对象实例,赋值给对象声明

如果有更严格的配置也可以把接口配置上去(不过没啥用)

    <bean id="fruit" class="com.Spring.Demo.IFruit" abstract="true"></bean>
    <bean id="apple" class="com.Spring.Demo.Apple" parent="fruit"></bean>

由于接口是抽象的,那么表示接口对象不会进行实例化。而在编写apple元素的时候加上的parent 也只是说明而已。

总结

spring是一个非常庞大的工厂,所有对象的实例化等赋值部分,不需要用户赋值处理了,全部交给spring完成。

用户只需要根据需求引用对象实例即可。

原文地址:https://www.cnblogs.com/alsf/p/7898695.html