IoC之HelloWorld

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值