Spring DI via setter method

本文展示了如何使用Spring框架通过setter方法实现组件间的依赖注入。包括接口定义、实现类、辅助类以及Spring配置文件的使用,最终通过运行代码验证依赖注入效果。

A simple Spring example to show you how to dependency inject a bean via setter method, the most common used DI method.

1. IOutputGenerator

An interface and implemntation class of it.

package com.mkyong.output;

public interface IOutputGenerator
{
    public void generateOutput();
}

package com.mkyong.output.impl;

import com.mkyong.output.IOutputGenerator;

public class CsvOutputGenerator implements IOutputGenerator {
    public void generateOutput() {
        System.out.println("This is Csv Output Generator");
    }
}

2. Helper class

A helper class, later use Spring to DI the IOutputGenerator.

package com.mkyong.output;

import com.mkyong.output.IOutputGenerator;

public class OutputHelper {
    IOutputGenerator outputGenerator;

    public void generateOutput() {
        outputGenerator.generateOutput();
    }

    //DI via setter method
    public void setOutputGenerator(IOutputGenerator outputGenerator) {
        this.outputGenerator = outputGenerator;
    }
}

3. Spring configuration

Configure bean in Spring configuration file, and reference the bean “CsvOutputGenerator” into “OutputHelper”, via property tag, ref attribute.
In this case, Spring will DI the bean “CsvOutputGenerator” into “OutputHelper” class, via setter method “setOutputGenerator(IOutputGenerator outputGenerator)”.

<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="OutputHelper" class="com.mkyong.output.OutputHelper">
        <property name="outputGenerator" ref="CsvOutputGenerator" />
    </bean>

    <bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />

</beans>

4. Run it

Load everything, and run it.

package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.output.OutputHelper;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "SpringBeans.xml");

        OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
                output.generateOutput();
    }
}

Output

This is Csv Output Generator
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值