Spring依赖注入_set注入_构造器注入_注解注入
属性setter方法注入_方式一(通用bean)_方法二(使用内部bean)_ 基本类型的注入_集合类型的注入
一、在beans.xml中,配置要被注入的bean.
二、在需要注入的bean配置中添加<property name="personDao" ref="personDao" />设置
1、被注入类接口 及 被注入的bean。
PersonDao.java
package com.dwt1220;
public interface PersonDao {
public abstract void add();
}
PersonDaoBean.java
package com.dwt1220;
public class PersonDaoBean implements PersonDao{
public void add(){
System.out.println("执行PersonDaoBean中的add()方法");
}
}
2.需要注入bean的类,及接口
PersonService.java
package com.dwt1220;
public interface PersonService {
public abstract void save();
}
PersonServiceBean.java
package com.dwt1220;
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void save() {
personDao.add();
}
}
3.beans.xml 配置文件 方式一(通用bean)
<?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.5.xsd">
<bean id="personDao1" class="com.dwt1220.PersonDaoBean" />
<bean id="personService" class="com.dwt1220.PersonServiceBean">
<!-- name 需要注入的变量名,ref beans.xml中注册的的bean的id或name -->
<property name="personDao" ref="personDao1" />
</bean>
</beans>
方法二(使用内部bean,但该bean不能被其他bean使用)
<?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.5.xsd">
<bean id="personService" class="com.dwt1220.PersonServiceBean">
<!-- 使用内部bean,但该bean不能被其他bean使用 -->
<property name="personDao">
<bean class="com.dwt1220.PersonDaoBean" />
</property>
</bean>
</beans>
4.Test.java
package com.dwt1220;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService) ctx.getBean("personService");
personService.save();
ctx.close();
}
}
基本类型的注入
在<bean>标签体内添加 <property name="string" value="stringvalue"/>。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XM