1.通过构造器
beans.xml
set和get构造
注解注入:
2.通过set和get方法
3.使用Filed注入(annocation)
构造器:
public interface PersonService {
public void save();
}
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
private String name;
public PersonServiceBean(PersonDao personDao, String name) {
super();
this.personDao = personDao;
this.name = name;
}
public void save() {
System.out.println(name);
personDao.add();
}
}
public interface PersonDao {
public void add();
}
public interface PersonDao {
public void add();
}
beans.xml
<bean id="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
<constructor-arg index="0" type="cn.itcast.dao.PersonDao" ref="personDao"></constructor-arg>
<constructor-arg index="1" value="高明"></constructor-arg>
</bean>
set和get构造
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<bean id="personDao" class="com.gaodml.spring.persondaoimpl.PersonDaoBean"></bean>
<bean id="personService" class="com.gaodml.spring.personserviceimpl.PersonServiceBean">
</bean>
</beans>
package com.gaodml.spring.personserviceimpl;
import javax.annotation.Resource;
import com.gaodml.spring.persondao.PersonDao;
import com.gaodml.spring.personservice.PersonService;
public class PersonServiceBean implements PersonService {
@Resource
private PersonDao personDao;
@Override
public void save(){
System.out.println("save()方法调用");
personDao.add();
}
public PersonServiceBean() {
}
}
注解注入:
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
<bean id="personDao" class="com.gaodml.spring.persondaoimpl.PersonDaoBean"></bean>
<bean id="personService" class="com.gaodml.spring.personserviceimpl.PersonServiceBean">
<constructor-arg index="0" ref="personDao"></constructor-arg>
</bean>