依賴:spring
在A類中引用了B類,說明A依賴於B。數組
注入:app
使用Spring框架給A類中的B對象的屬性賦值。框架
直接上代碼:ide
1.只使用IOCthis
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
<bean id="person" class="com.spring.demo1.Person"/>
/** * 只使用IOC */ @Test public void m01(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Person p = (Person) ac.getBean("person"); p.setAge(10); p.setName("10歲的boy"); System.out.println(p); }
2.使用IOC+DIspa
<bean id="person" class="com.spring.demo1.Person"> <property name="name" value="30歲的man"/> <property name="age" value="30"/> </bean>
/** * 使用IOC+DI */ @Test public void m02(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Person p = (Person) ac.getBean("person"); System.out.println(p); }
兩種注入方式code
1.經過setter方法注入------開發經常使用xml
上述的依賴注入方法↑↑↑↑↑↑↑↑↑對象
在編寫的JAVA類中加入屬性的set方法
配置文件:(property)
<bean id="person" class="com.spring.demo1.Person"> <property name="name" value="30歲的man"/> <property name="age" value="30"/> </bean>
2.經過構造方法注入
在編寫的JAVA類中加入有參構造方法
配置文件:(constructor-arg)
<bean id="person" class="com.spring.demo1.Person"> <constructor-arg name="name" value="40歲的person"/> <constructor-arg name="age" value="40"/> </bean>
注意:
若是屬性是另外一個JAVA類,應該將 value屬性 改成 ref
<bean id="car" class="com.spring.Car"/> <bean id="person" class="com.spring.Person"> <property name="name" value="man"/> <property name="car" ref="car"/> </bean>
數組,集合(List,Set,Map),Properties等的注入
1. 若是是數組或者List集合,注入配置文件的方式是同樣的 <bean id="collectionBean" class="com.spring.CollectionBean"> <property name="arrs"> <list> <value>呵呵</value> <value>哈哈</value> </list> </property> </bean> 2. 若是是Set集合,注入的配置文件方式以下: <property name="sets"> <set> <value>哈哈</value> <value>呵呵</value> </set> </property> 3. 若是是Map集合,注入的配置方式以下: <property name="map"> <map> <entry key="老王1" value="38"/> <entry key="老王2" value="38"/> <entry key="老王3" value="29"/> </map> </property> 4. 若是是properties屬性文件的方式,注入的配置以下: <property name="pro"> <props> <prop key="username">root</prop> <prop key="password">root</prop> </props> </property>