飞行的猪哼哼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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方式注入成功
posted on 2019-10-13 10:26  飞行的猪哼哼  阅读(41)  评论(0)    收藏  举报