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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值