您的位置:首页 > 编程语言 > Java开发

Spring 学习记录 2 Spring的依赖注入

2014-10-22 12:27 375 查看
上篇,我们用一个例子分析了依赖注入的作用。

这篇,将介绍最简单的 Spring 依赖注入。

用 Spring 时,你可能会很头大。

版本这么多,用哪个版本?

模块这么多,哪个是负责哪块?

这个我也不太清楚。

我使用 maven 管理依赖。

<dependencies>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.2.4.RELEASE</version>
  </dependency>
</dependencies>


Spring 中用容器来管理(创建和销毁)bean。

常用的容器是 org.springframework.context.ApplicationContext,它是个接口。

常用的实现有 org.springframework.context.support.ClassPathXmlApplicationContext。

建一个叫 ivo 的包,里面创建 Weapon 接口,BowAndArrow 类,Person 类,实现一如上篇。

Spring 的容器需要一个配置文件,来让它明白,该管理哪些 bean。

为了说明这个配置文件的命名是无所谓的,就命名 noname.xml 吧。

<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="weapon" class="ivo.BowAndArrow"/>
    <bean id="person" class="ivo.Person">
        <constructor-arg ref="weapon"/>
    </bean>

</beans>


这里就是把依赖注入,由代码形式改为了 xml 形式,有好处吗?

有个毛好处,一个类还得两处声明,但这就是 Spring 的规则。

使用到是更方便了,毕竟把一部分逻辑写到 xml 了。。。

public static void main(String[] args) {

        ApplicationContext applicationContext
                = new ClassPathXmlApplicationContext("noname.xml");
        Person person = (Person)applicationContext.getBean("person");
        person.killEnemy();
    }


Spring 配置的 bean 默认都是单例。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: