IoC之HelloWorld

来源:互联网 发布:拼豆豆图纸设计软件 编辑:程序博客网 时间:2024/06/08 19:45

IoC是控制反转,也被称为依赖注入。org.springframework.beans和org.springframework.context包是Spring框架IoC容器的基础。 BeanFactory接口管理任何类型对象。 ApplicationContext是BeanFactory子接口,web应用层中使用的WebApplicationContext

ClassPathXmlApplicationContext 或FileSystemXmlApplicationContextApplicationContext接口的实现类

配置

有三种配置方式,这里文章是基于XML配置方式

  • 基于XML文件配置
  • 基于注解的配置,从Spring2.5版本后引入的
  • 基于java的配置,从Spring3.0版本后引入的

xml配置:创建一个XML文件,根元素是beans。使用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"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="..." class="...">        <!-- 在这里写 bean 的配置和相关引用 -->    </bean></beans>

实体类

public class Greeting {    public void greeting(){        System.out.println("hello world!");    }}

在XML文件中配置

创建配置文件spring-ioc.xml。id指定唯一的名称,class指定类的全限定名称

<?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.xsd">    <bean id="greeting" class="com.devin.java.helloworld.Greeting"/></beans>

获取XML中配置对象

获得接口管理类对象,可以通过ClassPathXmlApplicationContext 或FileSystemXmlApplicationContext实现类来创建

ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/spring-ioc.xml"});
或者

ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"src/main/resources/spring/spring-ioc.xml"});

然后根据方法T getBean(String name, Class<T> requiredType) 方法,可以获得配置对象的实例

Greeting greeting = context.getBean("greeting", Greeting.class);        greeting.greeting();


引用文件路径问题

在beans中引用其他配置文件

<import resource="spring-other.xml"/>
在引用其他文件的路径是相对于本身文件所在目录,前面有/也是表示相对于本身文件所在目录。所以下面配置是一个效果
<import resource="spring-other.xml"/>    <import resource="/spring-other.xml"/>

也可以使用 ./ 表示当前目录

<import resource="./spring-other.xml"/>

也可以使用classpath:和classpath*:  这个两个区别http://blog.csdn.net/kkdelta/article/details/5507799

<import resource="classpath:spring/spring-other.xml"/>    <import resource="classpath*:spring/spring-other.xml"/>

创建容器接口对象时,也可以使用classpath

ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:spring/spring-ioc.xml"});        Greeting greeting = context.getBean("greeting", Greeting.class);        greeting.greeting();



0 0