您的位置:首页 > 编程语言 > Java开发

spring 注入bean的三种方式

2013-08-12 00:00 627 查看
在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,选择那种依个人爱好了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java spring