Spring 的IOC(一)

来源:互联网 发布:液压系统计算软件 编辑:程序博客网 时间:2024/05/01 17:31

Spring 的IOC(一)

核心jar包

<beans xmlns>

Xmlns:默认的默认空间

Xml

Spring中的配置文件可以有多个

//加载多个文件

ApplicationContext ac =new ClassPathXmlApplicationContext(new String[]{“applicationContext1.xml”,” applicationContext2.xml”})

ApplicationContext ac =new FileSystemXmlApplicationContext(new String[]{“src/applicationContext.xml”})

//IOC的控制翻转体现

GreetingService gs=( GreetingService)ac.getBean(“greeting1”);

Gs.getSay(); 

控制翻转:类交给系统来支配;而不是在类的内部控制,

依赖

      构造器的注入,通过构造器的类型匹配方法进行注入时,当类型相同时最好采用索引位置匹配法,xml中用<constructor-agr>标签注入

用构造器注入

1. 修改xml文件

<constructor-arg  index=“0”><!—可以有多个Constructor-arg标签,索引的位置是从0开始的-->

<value>value值</value>

</ cinstructor-arg >

 <constructor-arg type="java.lang.String">

       <value>你好!</value>

     </constructor-arg>

     

     <constructor-arg type="java.lang.String">

       <value>redarmy_chen</value>

     </constructor-arg>

Set方法注入:xml中用<propery>标签注入

<!--第一个类,id是xml中唯一的标识,class是该类的路径  -->

<bean id="greetingServiceImpl" class="cn.csdn.service.GreetingServiceImpl">

<!-- 设置第一个类中的属性的值 -->

<property name="say" value="hello"></property>

</bean>

<!-- 设置第二类 -->

<bean id="greetingServiceImpl2" class="cn.csdn.service.greetingServiceImpl2">

<!-- 设置第二个类的属性,因为它是类的对象,要用的ref -->

<property name="gsi" ref="greetingServiceImpl"></property>

</bean>

最好的注入方法是set注入的方法

Spring容器的访问,是通过下面的两个接口完成的

beanFactory:核心,开发者借助于配置文件(xml文件),尤其是在内存受限的情况下

ApplicationContext:它实现了BeanFactory接口

创建一个BeanFactory的时候就是对JavaBean的实例化、配置和管理

Resource是一个资源接口 fileSystemResource接口是Resource的一个实现类

BeanFactory是充当IOC的容器,本身是接口,XmlBeanFactory接口的实现类

 

原创粉丝点击