注入依赖对象
- 注入基本数据类型
通过value属性注入
在beans.xml文件中
<?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-2.0.xsd">
<bean id="PersonService" class="com.gc.service.impl.PersonServiceImpl">
<property name="name" value="nihao"></property>
</bean>
</beans>
在接口bean对象中
package com.gc.service.impl;
import com.gc.service.PersonService;
public class PersonServiceImpl implements PersonService {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void save() {
// TODO Auto-generated method stub
System.out.println("name:"+name);
System.out.println("save方法");
}
}
结果:
ref属性注入bean对象
- 注入集合类型
1.set集合
<?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-2.0.xsd">
<bean id="PersonService" class="com.gc.service.impl.PersonServiceImpl">
<property name="sets">
<set>
<value>first</value>
<value>second</value>
<value>third</value>
</set>
</property>
</bean>
</beans>
2.list集合
<?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-2.0.xsd">
<bean id="PersonService" class="com.gc.service.impl.PersonServiceImpl">
<property name="lists">
<list>
<value>first</value>
<value>second</value>
<value>third</value>
</list>
</property>
</bean>
</beans>
3.property
<?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-2.0.xsd">
<bean id="PersonService" class="com.gc.service.impl.PersonServiceImpl">
<property name="propertys">
<props>
<prop key="key1">first1</prop>
<prop key="key2">first2</prop>
<prop key="key3">first3</prop>
</props>
</property>
</bean>
</beans>
4.map类型
<?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-2.0.xsd">
<bean id="PersonService" class="com.gc.service.impl.PersonServiceImpl">
<property name="maps">
<map>
<entry key="key1" value="value1" />
<entry key="key2" value="value2" />
<entry key="key3" value="value3" />
</map>
</property>
</bean>
</beans>