1.使用set方法注入
<bean id="video" class="work.yspan.sp.domain.Video" scope="singleton">
<property name="id" value="9"/>
<property name="title" value="Spring 5.x课程"/>
</bean>
测试代码:
public class App {
public static void main(String[] args){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
testInject(applicationContext);
}
//注入测试
private static void testInject(ApplicationContext applicationContext){
Video video=(Video) applicationContext.getBean("video");
System.out.println(video.getTitle());
}
测试结果截图:
2.使用带参的构造函数注入
<bean id="video" class="work.yspan.sp.domain.Video">
<constructor-arg name="title" value="spring5.x带参注入课程"></constructor-arg>
</bean>
测试代码同上:
测试效果截图:
3.POJO类型注入(property 没有使用value属性,而是使用了ref属性)
<bean id="video" class="work.yspan.sp.domain.Video">
<constructor-arg name="title" value="spring5.x带参注入课程"></constructor-arg>
</bean>
<bean id="videoOrder" class="work.yspan.sp.domain.VideoOrder">
<property name="id" value="8"/>
<property name="outTradeNo" value="165xa1s1afa51"/>
<property name="video" ref="video"/>
</bean>
测试代码:
//注入测试
private static void testInject(ApplicationContext applicationContext){
Video video=(Video) applicationContext.getBean("video");
System.out.println(video.getTitle());
VideoOrder videoOrder=(VideoOrder) applicationContext.getBean("videoOrder");
System.out.println(videoOrder.getVideo().getTitle());
}
测试效果截图:
4.List-Map注入
<bean id="video" class="work.yspan.sp.domain.Video">
<!--list方式注入-->
<property name="chapterList">
<list>
<value>第一章xxx</value>
<value>第二章xxx</value>
<value>第三章xxx</value>
</list>
</property>
<!--Map方式注入-->
<property name="videomap">
<map>
<entry key="1" value="1xxx"></entry>
<entry key="2" value="2xxx"></entry>
<entry key="3" value="3xxx"></entry>
</map>
</property>
</bean>
测试代码:
//注入测试
private static void testInjectCollection(ApplicationContext applicationContext){
Video video=(Video) applicationContext.getBean("video");
System.out.println(video.getChapterList().toString());
System.out.println(video.getVideomap().values().toString());
}
测试效果截图: