一个完整的Bean配置文档


 
 
  
  
  
  
    
   
   
     
    
    
     
     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;
    }
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值