标签:none opened cat contex void text nbsp users app
1. DI的概念
* DI -- Dependency Injection,依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件中!!
2. applicationContext.xml配置信息,如下:
1 <bean id="userDao" class="com.demo.service.UserDaoImpl"></bean> 2 3 <bean id="userService" class="com.demo.service.UserServiceImpl"> 4 <!-- 依赖注入 --> 5 <property name="userDao" ref="userDao"></property> 6 </bean>
3. 代码示例:
1 UserServiceImpl: 2 public class UserServiceImpl implements UserService { 3 4 // 提供成员属性,提供set方法 5 private UserDao userDao; 6 public void setUserDao(UserDao userDao) { 7 this.userDao = userDao; 8 } 9 10 @Override 11 public void sayHello() { 12 userDao.sayHello(); 13 } 14 15 } 16 17 UserDaoImpl: 18 public class UserDaoImpl implements UserDao { 19 20 @Override 21 public void sayHello() { 22 System.out.println("Dao Hello!"); 23 } 24 25 } 26 27 Demo: 28 public class Demo2 { 29 30 @Test 31 public void run() { 32 // 创建工厂,加载配置文件 33 ApplicationContext context = new ClassPathXmlApplicationContext("/config/spring-mvc.xml"); 34 // 获取对象 35 UserService userService = (UserService) context.getBean("userService"); 36 // 调用方法 37 userService.sayHello(); 38 } 39 40 }
标签:none opened cat contex void text nbsp users app
原文地址:https://www.cnblogs.com/liyue-sqsf/p/9011859.html