spring 依赖性注入 (spring 依赖性注入(xml配置文件,填写的时候要写全,不是包,而是到类)

来源:互联网 发布:linux expr 编辑:程序博客网 时间:2024/05/17 02:40

cn.dao

package cn.dao;public interface PersonDao {public abstract void add();}

cn.dao.imp

package cn.dao;public interface PersonDao {public abstract void add();}

cn.service

package cn.service;public interface PersonService {public abstract void save();}

cn.service.imp

package cn.service.imp;import org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor;import cn.dao.PersonDao;import cn.service.PersonService;public class PersonServiceBean implements PersonService {private PersonDao personDao;public PersonDao getPersonDao() {return personDao;}public void setPersonDao(PersonDao personDao) {this.personDao = personDao;}public void save(){System.out.println("执行save()方法");personDao.add();}}

junit.test

package junit.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.service.imp.PersonServiceBean;public class SpringTest {@Test public void instanceSpring(){AbstractApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"beans.xml"});PersonServiceBean personServiceBean=(PersonServiceBean) ctx.getBean("personService");personServiceBean.save();ctx.close();}}

beans.xml

<?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="personDao"  class="cn.dao.imp.PersonDaoBean"></bean>  <bean id="personService" class="cn.service.imp.PersonServiceBean">  <property name="personDao" ref="personDao"></property>  </bean></beans>



原创粉丝点击