spring的常用的注入方式

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());

    }

测试效果截图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值