[java]
view plain
copy
print
?
- import cn.itm.dao.PersonDao;
-
-
- public class PersonDaoBean implements PersonDao {
-
-
- public void add(){
- System.out.println("执行PersonDaoBean的add方法。。。");
- }
- }
[java]
view plain
copy
print
?
- package cn.itm.dao;
-
- public interface PersonDao {
-
- public abstract void add();
-
- }
[java]
view plain
copy
print
?
- package cn.itm.service.impl;
-
- import cn.itm.dao.PersonDao;
- import cn.itm.service.PersonService;
-
- public class PersonServiceBean implements PersonService{
-
-
- private PersonDao personDao;
-
-
- public void setPersonDao(PersonDao personDao) {
- this.personDao = personDao;
- }
-
-
- public void save(){
-
- personDao.add();
- }
-
- }
[java]
view plain
copy
print
?
- package cn.itm.service;
-
- public interface PersonService {
-
- public abstract void save();
-
- }
[java]
view plain
copy
print
?
- <?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:
- http:
-
- <bean id="personDao" class="cn.itm.dao.impl.PersonDaoBean"></bean>
-
- <bean id="personService" class="cn.itm.service.impl.PersonServiceBean" >
- <!-- 实现 注入 -->
- <property name="personDao" ref="personDao"></property>
- </bean>
-
-
- </beans>
测试类:
[java]
view plain
copy
print
?
- package junit.test;
-
-
- import org.junit.BeforeClass;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import cn.itm.service.PersonService;
-
- public class SpringTest {
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- }
-
-
- @Test public void instanceSpring(){
-
- ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
- PersonService personService = (PersonService) ctx.getBean("personService");
- personService.save();
-
- }
- }
成功。
利用setter方式的好处:可以被多个bean使用。
下面利用编码剖析Spring依赖注入的原理:
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|