标签:
Spring实现依赖注入有几种方式。
基本类型对象注入
package test.spring.dao;
public interface PersonDao {
public abstract void add();
}package test.spring.dao.impl;
import test.spring.dao.PersonDao;
public class PersonDaoBean implements PersonDao {
@Override
public void add(){
System.out.println("执行PersonDaoBean里的test1()方法");
}
}package test.spring.service;
public interface PersonService {
public abstract void save();
}package test.spring.service.impl;
import test.spring.dao.PersonDao;
import test.spring.service.PersonService;
public class PersonServiceBean2 implements PersonService {
private PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
@Override
public void save(){
personDao.add();//与具体的PersonDaoBean无关,实现真正的解耦
}
}
<!-- 基本类型对象注入 --> <bean id="personDao" class="test.spring.dao.impl.PersonDaoBean"></bean> <bean id="personService" class="test.spring.service.impl.PersonServiceBean2"> <!-- name是service中对于的属性名,ref是对于的bean --> <property name="personDao" ref="personDao"></property> </bean>
package test.spring.jnit;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.spring.service.PersonService;
public class SpringTest2 {
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"beans.xml");
PersonService personService=(PersonService) applicationContext.getBean("personService");
personService.save();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,请注明出处:http://blog.csdn.net/lindonglian
标签:
原文地址:http://blog.csdn.net/lindonglian/article/details/47024259