只需使用注释即可在弹簧中实现松耦合 - 避免使用xml

时间:2017-06-08 10:02:49

标签: java spring dependency-injection interface loose-coupling

我已经从https://www.mkyong.com/spring/spring-loosely-coupled-example/了解了一个例子。 下面的示例使用bean来实现松散耦合。 我们如何使用注释而不是bean来实现相同的松散耦合?

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("Csv Output Generator");
    }
}

package com.mkyong.output.impl;
import com.mkyong.output.IOutputGenerator;
public class JsonOutputGenerator implements IOutputGenerator
{
    public void generateOutput(){
        System.out.println("Json Output Generator");
    }
}


package com.mkyong.output;
import com.mkyong.output.IOutputGenerator;
public class OutputHelper
{
    IOutputGenerator outputGenerator;

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

    public void setOutputGenerator(IOutputGenerator outputGenerator){
        this.outputGenerator = outputGenerator;
    }
}

Spring-Common.xml

<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" />
<bean id="JsonOutputGenerator" 
    class="com.mkyong.output.impl.JsonOutputGenerator" />
</beans>

主要课程

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(new String[] {"Spring-
           Common.xml"});

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

    }
}

0 个答案:

没有答案