Spring框架学习(2):基于全类名的方式配置bean

来源:互联网 发布:华南理工大学软件学院 编辑:程序博客网 时间:2024/06/04 19:57

bean的配置形式有两种,分别是基于XML文件的方式和基于注解的方式,这篇文章主要讲基于XMl文件的配置形式。

一、属性注入

其实在上次的Spring HelloWorld程序中使用的就是属性注入的方式:

 

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 配置bean --><bean id="helloWorld" class="beans.HelloWorld"><property name="name" value="CSDN"></property></bean></beans>

Id用于唯一标注该beanclass是指定要实例化哪个类,通过反射的方式在IOC容器中创建bean,要求要有无参数的构造器,property用于设定bean的属性,其中name应该对应成员变量的setter函数,即如果setter函数是setName()那么name=”name”,如果是setName2()那么name=”name2”,注意不是和成员变量名称一致而是与setter函数名称一致,value显然是用于赋值。

main方法中可以通过以下两种方式得到bean的实例

 

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");HelloWorld helloWorld = ctx.getBean(HelloWorld.class);HelloWorld helloWorld2 = (HelloWorld)ctx.getBean("helloWorld");

应该注意的是使用getBean(Class<T> requireType)时要求Bean容器中,该类只有唯一的一个实例化对象,使用getBean(String name)方式时是通过xml文件中beanid来获取实例化对象,要注意加上类型转换。

二、构造方法注入

将前面的HelloWorld类中的setter方法去掉,加入带参的构造方法

  

package beans;public class HelloWorld {private String name;public HelloWorld(String name) {super();this.name = name;}public void hello() {System.out.println("hello: " + name);}}

bean的配置文件中使用constructor-arg来对成员变量赋值

 

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 配置bean --><bean id="helloWorld" class="beans.HelloWorld"><constructor-arg value="csdn"></constructor-arg></bean></beans>

constructor-arg中没有name属性,如果构造器中有多个输入参数,可以用index来指定参数的顺序(不使用时默认为按照0,1,2..的顺序),

<constructor-arg value="csdn" index="0"></constructor-arg>

当多个构造函数的参数个数相同,但是参数类型不同时,可以使用type来指定输入参数的类型

 

<constructor-arg value="csdn" type="java.lang.String"></constructor-arg>

以上便是两种常用的注入方法。


0 0
原创粉丝点击