HelloWorld 这里在配置bean的时候都指明了id,id是这个bean在配置文件中的唯一标识,当然也可以使用name,下面说说它们之间的区别:
id属性是在配置文件中标识Bean的,name属性则可以用来指定这个Bean的别名。因为XML规范对于id的合法字符有严格的规定,所以当用非法字符来配置id时候就不行了,这个时候可以通过name属性来解决。同时通过name属性可以指定多个id,这些id要用都好或者分号分割。在Spring中,Bean可以被定义为两种模式:单例模式和非单例模式(singleton or non-singleton)。而Spring默认的是单例模式,何谓单例模式,就是这个Bean只有一个实例存在,而不管有多少个对这个Bean的请求。而非单例模式则回在每次对这个Bean的请求中产生新的实例。简单的说就是:singleton只会被new一次,而non-singleton却在每次请求的时候都new一次。这就是区别。
package com.gc.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.gc.action.HelloWorld; public class TestHelloWorld { public static void main(String args[]) { ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml"); HelloWorld helloWorld=(HelloWorld)actx.getBean("helloWorld"); System.out.println(helloWorld.getDate()+" "+helloWorld.getMsg()); } }package com.gc.action; import java.util.Date; public class HelloWorld { private String msg=null; private Date date=null; public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } /* public HelloWorld(String msg) { this.msg=msg; } 调试可知:构造函数存在,则在config.xml中比增加constuctor属性 */ public void setMsg(String msg) { this.msg=msg; } public String getMsg() { return this.msg; } }