码迷,mamicode.com
首页 > 其他好文 > 详细

使用构造器装配属性

时间:2015-07-24 00:00:44      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:

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="test.spring.dao.impl.PersonDaoBean" />
    <bean id="personService" class="test.spring.service.impl.PersonServiceBean3">
        <constructor-arg index="0" type="test.spring.dao.PersonDao" ref="personDao"/>
        <constructor-arg index="1" value="LinDL"/>
    </bean>

</beans> 

PersonDao

package test.spring.dao;

public interface PersonDao {

    public abstract void add();

}

PersonDaoBean

package test.spring.dao.impl;

import test.spring.dao.PersonDao;


public class PersonDaoBean implements PersonDao {

    @Override
    public void add(){
        System.out.println("执行PersonDaoBean里的test1()方法");
    }
}

PersonService2

package test.spring.service;

public interface PersonService2 {

    public abstract void save();
}

PersonServiceBean3(通过构造器装配属性)

package test.spring.service.impl;

import test.spring.dao.PersonDao;
import test.spring.service.PersonService2;

public class PersonServiceBean3 implements PersonService2 {

    private PersonDao personDao;
    private String name;

    public PersonServiceBean3(PersonDao personDao, String name) {
        this.personDao = personDao;
        this.name = name;
    }

    public PersonDao getPersonDao() {
        return personDao;
    }

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void save() {
        // TODO Auto-generated method stub
        personDao.add();
        System.out.println(name);
    }
}

客户端

package test.spring.jnit;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.spring.service.PersonService;
import test.spring.service.PersonService2;

public class SpringTest2 {
    @Test
    public void test2() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "beans.xml");
        PersonService2 personService = (PersonService2) applicationContext
                .getBean("personService");
        personService.save();
    }

}

版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,请注明出处:http://blog.csdn.net/lindonglian

使用构造器装配属性

标签:

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

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