码迷,mamicode.com
首页 > 其他好文 > 详细

依赖注入

时间:2018-05-28 16:07:18      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:src   framework   contex   nts   getbean   version   package   imp   support   

 

1.

技术分享图片

2.Test.java

package com.inspur;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
        Userdao userDao =(Userdao) application.getBean("userId");
        userDao.say();
        
        UserService userService = (UserService)application.getBean("userService");
        userService.say();
        

    }

}

3.Userdao.java

package com.inspur;

public interface Userdao {
    public void say();

    

}

4.UserDaoImpI.java

package com.inspur;

public class UserDaoImpI implements Userdao {

    public void say() {
        // TODO Auto-generated method stub
        System.out.println("Spring say hello world");
    }

}

5.UserService.java

package com.inspur;

public interface UserService {
    public void say();

}

5.UserServiceImpl.java

package com.inspur;

public class UserServiceImpL implements UserService {
    private Userdao userDao;

    public void setUserDao(Userdao userDao) {
        this.userDao = userDao;
    }

    public void say(){
        System.out.println("UserServiceImpL say Hello world");
    }

}

6.applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
    <bean id="userId" class="com.inspur.UserDaoImpI">
    </bean>
    <bean id="userService" class="com.inspur.UserServiceImpL">
    <property name="userDao" ref="userId"></property>
    </bean>
</beans>

技术分享图片

name=“userDao"是UserServiceImpl的技术分享图片

ref="userId"是技术分享图片

 

依赖注入

标签:src   framework   contex   nts   getbean   version   package   imp   support   

原文地址:https://www.cnblogs.com/sunxiaoyan/p/9100386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!