Spring中基于package的扫描流入

Spring中基于package的扫描注入
一.概述

在Spring中IOC是一个非常重要的概念,在平时写程序时经常会出现一个对象依赖另外一个对象的,其实这种依赖关系在程序中不是很重要,重要的是在使用依赖对象的时候依赖对象是正常的。Spring容器管理了这种依赖关系,保证了依赖的对象在使用的时候是正常的,加入A要依赖B,我们只要把这种依赖关用一种Spring中提供的方式表达出来,这时候Spring容器就能识别出这种依赖关系,同时会把B给注入到A,保证在A中使用B的时候,B是正常的,在Spring中提供了一种基于包扫描的注入方式,我们只需要用一些注解就可以轻松实现对象的注入。详见下面的代码。

二.代码实现
package ioc.component;

public interface IFXNewsPersister {

}

package ioc.component;

public interface IFXNewsListener {

}

package ioc.component;

import org.springframework.stereotype.Component;

@Component
public class DowJonesNewsListener implements IFXNewsListener {

}

package ioc.component;

import org.springframework.stereotype.Component;

@Component
public class DowJonesNewsPersister implements IFXNewsPersister {

}


package ioc.component;

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

public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("...component-bean.xml");
        FXNewsProvider newsProvider = (FXNewsProvider)ctx.getBean("FXNewsProvider");
        newsProvider.getNewsListener();
        System.out.println(newsProvider.info());
    }
}

<?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:context="http://www.springframework.org/schema/context"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
	   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	   http://www.springframework.org/schema/context
	   http://www.springframework.org/schema/context/spring-context-2.5.xsd
	   http://www.springframework.org/schema/tx
	   http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	   
	   <!-- 基于package包的扫描注入 -->
	   <context:component-scan base-package="ioc.component" />
</beans>

三.注意点

1.Autowire按照类型注入


2.Resource按照名字注入,如果找不到名字再按照类型注入,推荐使用@Reource(name="xx"),强制使用名字为xx的bean来注入,如果没有名字为xx的bean的话,注入就是失败的,但是要是遇见同类型的bean,也能注入,这样就会事与愿违。


3.要想被Spring容器扫描,就得现在xml文件中指定要扫描的包,同时也要在需要被扫描的类上面打上@Component标签,不打的话,不会被扫描到。