spring 注入bean的三种方式

在spring xml配置中有三种方式注入bean元素

1.普通的

2.简短的

3.“p” 模式

首先定义一个简单的bean类

public class Bean{
  private String name;
  private String type;

  setter(..);
  getter(..);
}
1.普通的

通过value标签 注入 以property标签表示结束

<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-2.5.xsd">
 
	<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator">
		<property name="name">
			<value>mkyong</value>
		</property>
		<property name="type">
			<value>txt</value>
		</property>
	</bean>
</beans>
2.简短的

通过value 属性注入

<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-2.5.xsd">
 
	<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator">
		<property name="name" value="mkyong" />
		<property name="type" value="txt" />
	</bean>
 
</beans>
3.“p” 模式

把“p” 模式作为属性来注入

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator" 
             p:name="mkyong" p:type="txt" />
 
</beans>
注意在上面的配置文件中  xmlns:p=”http://www.springframework.org/schema/p 这个声明

三种方式都可以成功注入bean,选择那种依个人爱好了

转载于:https://my.oschina.net/igeeker/blog/152198

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值