<bean id="greeting" class="lm.proctice.spring.demo.Impl.HelloServiceImpl" scope="prototype"> ...... </bean>
1.id属性
id属性用来唯一标识<bean>标签,是<bean>标签中的最基本属性。
2.class属性
用来表示类的全名,通常为package.classname,本例中,我的package为lm.proctice.spring.demo.Impl,类名为HelloServiceImpl
3.scope属性
默认情况下,如果不设置scope属性,那么默认为singleton,即单实例模式,也就是说对于同一个Bean,多次调用getBean方法返回的都是同一个Bean对象,例如下面的代码输出相同的结果:
System.out.println(context.getBean("greeting").hashCode()); System.out.println(context.getBean("greeting").hashCode());输出:
604378607 604378607如果指明scope的值,如本例中指定为prototype,那么当每次的使用getBean方法时都会获得一个新的Bean对象,这样再执行下面的两行代码时,就有不同的输出:
System.out.println(context.getBean("greeting").hashCode()); System.out.println(context.getBean("greeting").hashCode());输出:
749550947 563692927
4.name属性
除了例子中给出的三个属性外,<bean>标签还有一个name属性比较常见,该属性主要是设置<bean>标签的别名,可以使用name属性来取代id属性
例如给本例中的<bean>标签设置一个name:
<bean id="greeting" name="one,two three;" class="lm.proctice.spring.demo.Impl.HelloServiceImpl" scope="prototype"> ...... </bean>在获得装配对象HelloService时可以写成:
HelloService hello=(HelloService)context.getBean("one");使用name的值
注:如果有多个别名(允许有多个别名),通过逗号(,),空格和分号(;)来分隔,也可以混合使用,例如例子中的写法。