spring的常用的注入方式

spring的常用的注入方式,第1张

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">
        
        <property name="chapterList">
            <list>
                <value>第一章xxxvalue>
                <value>第二章xxxvalue>
                <value>第三章xxxvalue>
            list>
        property>
        
        <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());

    }

测试效果截图:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/723335.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存