Spring基础:快速入门spring(4):setter注入

spring可以使用构造注入/setter方法/java注解等,本文通过实例来学习一下setter注入的方法。

这里写图片描述

定义注入依赖的interface

package com.liumiao.demo.spring;

public interface TeachingService {
    public String provideTeachingService();
}

定义注入依赖的类

package com.liumiao.demo.spring;

public class SwimmingTeachingService implements TeachingService {
    @Override
    public String provideTeachingService(){
        return "I provide service of teaching swimming.";
        }
}

修改Student类

作如下修改,注意如下两点

注意事项 详细
No.1 setter方式需要有缺省的构造函数
No.2 set函数和变量名的大小写规范
package com.liumiao.demo.spring;

public class Student implements Person {
    private TeachingService teachingService;
    public Student(){
        System.out.println("Student Default construct is called...");
    }
    public void setTeachingService(TeachingService service){
        teachingService=service;
    }
    @Override
    public String sayhello(){
        return "Hello, I am a student.";
    }
    @Override
    public String provideTeachingService(){
        return "I teach how to study...";
    }
}

配置spring设定文件

如下修改配置文件

注意事项 详细
No.1 ref和bean id的一致
No.2 property name和setter对象的一致
<?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.xsd">

    <bean id="thePerson" class="com.liumiao.demo.spring.Student">
        <property name="teachingService" ref="theService"></property>
    </bean>

    <bean id="theService" class="com.liumiao.demo.spring.SwimmingTeachingService">
    </bean>

</beans>

执行结果

TestDemo无需修改可以直接确认结果。

十一月 26, 2016 7:27:59 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@25f38edc: startup date [Sat Nov 26 19:27:59 CST 2016]; root of context hierarchy
十一月 26, 2016 7:27:59 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/liumiao/demo/spring/spring-cfg.xml]
Student Default construct is called...
Hello, I am a student.
I teach how to study...十一月 26, 2016 7:27:59 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@25f38edc: startup date [Sat Nov 26 19:27:59 CST 2016]; root of context hierarchy
发布了920 篇原创文章 · 获赞 1260 · 访问量 389万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览