依赖注入

Posted sunshine_96

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了依赖注入相关的知识,希望对你有一定的参考价值。

 

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"是

 

以上是关于依赖注入的主要内容,如果未能解决你的问题,请参考以下文章

spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段

Android Dagger片段可以访问AppModule和ActivityModule依赖关系,但不能访问FragmentModule依赖关系

以下代码片段是不是容易受到 Rails 5 中 SQL 注入的影响?

Eclipse OSGi 包需要另一个包的片段

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段