srping依赖注入的原理是根据sprin.xml配置文件中的bean生成容器,然后在使用时从容器中生成类的实例而不需要在内存中new出来。
一般方法是写<bean>在配置文件中,然后就可以在要调用该类,声明时,使用@Resource(name="xx")生成该类的实例了
例如:
@Resource(name = "test")
private Test test;
还可以使用注解,不用在配置中写<bean>,但是配置文件有所改动:(这是整合了cxf的)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
关键是添加这句:
<context:component-scan base-package="com" />
那么就可以在需要注入的类上使用
@Component("test")
public class Test {
即可