text 标签 引用 9.png ide .text sys 技术分享 对象
当容器调用一个无参的构造函数或一个无参的静态factory方法来初始化你的bean后,通过容器在你的bean上调用设值函数,基于设值函数的DI就完成了。
下面是TextEditor.java:
- package com.tuorialsponit;
- public class TextEditor {
- private SpellChecker spellChecker;
- public void spellCheck() {
- spellChecker.checkSpelling();
- }
- public SpellChecker getSpellChecker() {
- return spellChecker;
- }
- public void setSpellChecker(SpellChecker spellChecker) {
- System.out.println("Inside setSpellChecker");
- this.spellChecker = spellChecker;
- }
- }
SpellChecker.java
- package com.tuorialsponit;
- public class SpellChecker {
- public SpellChecker() {
- System.out.println("Inside SpellChecker constructor.");
- }
- public void checkSpelling() {
- System.out.println("Inside checkSpelling.");
- }
- }
MainApp.java文件的内容:
- public static void main(String[] args) {
- ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
- // HelloWorld obj1 = (HelloWorld) context.getBean("helloworld");
- // System.out.println(obj1.getMessage1());
- // System.out.println(obj1.getMessage2());
- //
- // System.out.println("-----------------------");
- // HelloIndia obj2 = (HelloIndia) context.getBean("helloIndia");
- // System.out.println(obj2.getMessage1());
- // System.out.println(obj2.getMessage2());
- // System.out.println(obj2.getMessage3());
- // String message = obj.getMessage();
- // System.out.println(message);
- TextEditor textEditor = (TextEditor) context.getBean("textEditor");
- textEditor.spellCheck();
- }
配置文件beans.xm的内容:
- <bean id="textEditor" class="com.tuorialsponit.TextEditor">
- <!-- <constructor-arg ref="spellChecker"></constructor-arg> -->
- <property name="spellChecker" ref="spellChecker">
- </property>
- </bean>
- <bean id="spellChecker" class="com.tuorialsponit.SpellChecker">
- </bean>
你应该注意定义在基于构造函数注入和基于设置函数注入中beans.xml文件的区别。唯一的区别在于使用的标签元素不同。第二个你需要注意的点是,如果你要把一个引用传递给一个对象,那么你需要使用标签的ref属性,而如果你要直接传递一个值,那么你应该使用value属性。
运行结果:
Spring-基于设置函数的依赖注入
text 标签 引用 9.png ide .text sys 技术分享 对象
原文:http://www.cnblogs.com/fangpengchengbupter/p/7817020.html
来源: http://www.bubuko.com/infodetail-2390343.html