忘了问问题了.呵呵.书上的例子上用的是PROPERTY.当初照着例子写的时候就报错 .后来看到后面把CONFIG.XML改成了CONSTRUCTOR-ARG它就好了.就想问下SET注入和构造注入的区别是什么?格式上,用法和作用上...谢谢...

解决方案 »

  1.   

    spring鼓励使用set进行注入,至于如何选择因情况而定,假如形式参数比较多的话,用构造注入的话参数列表就比较长了,建议还是使用set注入!呵呵
      

  2.   

    个人认为和spring的生命周期有关吧!因为bean是首先加载构造函数的!
      

  3.   

    你看的是什么书? 这么烂?
    看看<<spring live>>,下面的链接是我翻译的前四章,虽然比较老,但是我认为这是个非常好的入门教材@_@
    http://www.blogjava.net/xmlspy/articles/20244.html
    如果你使用set方式注入,你的bean必须有默认的无参构造函数,应该好好看看spring的文档!!
    你的类中有一个带有参数的构造函数,这就使得默认的无参构造函数没有了!!!
    java构造参数的规则是:
    1.如果你任何构造函数都不写,实际上系统会隐式地加上无参构造函数.
    2.如果你写了一个带有参数的构造函数,而没有写无参构造函数,系统并不会为你加上无参构造函数的
    3.如果写了无参构造函数,则系统使用你写的这个构造函数
    更改后的全部代码如下(win2003SP1,eclipse3.3,spring2.0),测试通过:public class HelloWorld {
    public String msg = null; //必须把无参构造函数手动加上
    public HelloWorld(){ }
    public HelloWorld(String msg) {
    this.msg = msg;
    } public void setMsg(String msg) {
    this.msg = msg;
    } public String getMsg() {
    return this.msg;
    }
    }
    --------------------------------------------------------<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
    <bean id="HelloWorld" class="HelloWorld"><!--属性class加上你的包前缀  -->
    <!-- 这是使用set方式注入的 -->
    <property name="msg">
    <value>Marco. is not a good boy!!!!</value>
    </property>
    </bean>
    </beans>----------------------------------------------------------------------------------import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;//此类没有任何更改
    public class TestHelloWorld {
    public static void main(String[] aegs) {
    ApplicationContext actx = new FileSystemXmlApplicationContext("config.xml");
    HelloWorld H = (HelloWorld) actx.getBean("HelloWorld");
    System.out.println(H.getMsg());
    }
    }
      

  4.   

    kao,这个问题竟然没有分 :)