在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,选择那种依个人爱好了
本文介绍了Spring XML配置中三种bean元素注入方法:普通注入、简短注入和“p”模式注入,并提供了详细的配置示例。
1万+

被折叠的 条评论
为什么被折叠?



