UserDao 接口
package com.student.ioc;
public interface UserDao {
public void say();
}
UserDaoImpl 实现了UserDao接口
package com.student.ioc;
public class UserDaoImpl implements UserDao {
@Override
public void say() {
System.out.println("我爱你,摸摸哒");
}
}
UserService接口
package com.student.ioc;
public interface UserService {
public void say();
}
UserserviceImpl 实现了UserService接口
package com.student.ioc;
public class UserDaoImpl implements UserDao {
@Override
public void say() {
System.out.println("我爱你,摸摸哒");
}
}
applicationContext 主配置文件
<?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">
<!-- services -->
<bean id="userDao" class="com.student.ioc.UserDaoImpl">
</bean>
<!-- more bean definitions for services go here -->
<bean id="userService" class="com.student.ioc.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
TestDI 测试类
package com.student.ioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDI {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService =(UserService)applicationContext.getBean("userService");
userService.say();
}
}
依赖注入:将对象(UserDao)注入到Bean当中。
理解:传统的方式,如果要是在UserServiceImpl中调用UserDaoImpl中的say()方法,就需要在UserServiceImpl中new一个UserDaoImpl对象,然后再调用UserDaoImpl中的方法。 现在:我们只需要将通过bean在配置文件中将UserDao注入到UserService中,然后UserServiceImpl中的set方法会直接创建UserDaoImpl这个对象。这样就相当于把UserDaoImpl注入到UserServiceImple中去了。
运行结果:
十月 13, 2019 10:09:30 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@46f7f36a: startup date [Sun Oct 13 10:09:30 CST 2019]; root of context hierarchy
十月 13, 2019 10:09:30 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
我爱你,摸摸哒
哈哈set方式注入成功
浙公网安备 33010602011771号