代码改变世界

Spring使用Setter依赖注入

2016-07-30 18:03  faunjoe88  阅读(415)  评论(0编辑  收藏  举报

一个简单的Spring例子来展示如何通过setter方法注入依赖项,最常用DI方法注入bean。

   1. IOutputGenerator

  接口和实现类  
1 package faj.test.javademo.set;
2 
3 /**
4  * Created by JiaGao on 2016/7/30.
5  */
6 public interface IOutputGenerator {
7     void generateOutput();
8 }
 1 package faj.test.javademo.set;
 2 
 3 /**
 4  * Created by JiaGao on 2016/7/30.
 5  */
 6 public class CsvOutputGenerator implements IOutputGenerator {
 7     @Override
 8     public void generateOutput() {
 9         System.out.println("This is Csv Output Generator");
10     }
11 }

   2. Helper类

一个辅助类,之后使用Spring 来注入 IOutputGenerator。  
 1 package faj.test.javademo.set;
 2 
 3 public class OutputHelper {
 4     private IOutputGenerator outputGenerator;
 5     public void generateOutput() {
 6         outputGenerator.generateOutput();
 7     }
 8     //DI via setter method
 9     public void setOutputGenerator(IOutputGenerator outputGenerator) {
10         this.outputGenerator = outputGenerator;
11     }
12 }

   3. Spring配置

配置Bean在Spring配置文件,并引用Bean “CsvOutputGenerator” 到 “OutputHelper”,通过property 和 ref 标签。

在这种情况下,Spring将通过setter方法注入Bean “CsvOutputGenerator” 到“OutputHelper”类,

“setOutputGenerator(IOutputGenerator outputGenerator)”.  

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 7            http://www.springframework.org/schema/context
 8                http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 9     <bean id="CsvOutputGenerator" class="faj.test.javademo.set.CsvOutputGenerator" />
10 
11     <bean id="OutputHelper" class="faj.test.javademo.set.OutputHelper">
12         <property name="outputGenerator" ref="CsvOutputGenerator" />
13     </bean>
14 </beans>

   4. 执行结果

载入一切东西,并运行它。  
 1 package faj.test.javademo.set;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 /**
 7  * Created by JiaGao on 2016/7/30.
 8  */
 9 public class App1 {
10     public static void main(String[] args) {
11         ApplicationContext context = new ClassPathXmlApplicationContext("faj/test/javademo/set/applicationContext.xml");
12         OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
13         output.generateOutput();
14     }
15 }

   输出结果

This is Csv Output Generator