码迷,mamicode.com
首页 > 编程语言 > 详细

Spring(五)依赖注入

时间:2015-07-23 17:57:38      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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

Spring(五)依赖注入

标签:

原文地址:http://blog.csdn.net/lindonglian/article/details/47024259

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!