SSM学习02依赖注入的实现方式

用上一篇博客所建立的项目继续:

Userservice

1 package com.zyk.ioc;
2 
3 public interface UserService {
4     public void say();
5 
6     
7 }

UserServiceImpl

 1 package com.zyk.ioc;
 2 
 3 public class UserServiceImpl implements UserService {
 4     private UserDao userDao;
 5     
 6     public UserDao getUserDao() {
 7         return userDao;
 8     }
 9 
10     public void setUserDao(UserDao userDao) {
11         this.userDao = userDao;
12     }
13 
14     public void say() {
15         // TODO Auto-generated method stub
16         this.userDao.say();
17         System.out.println("userservice hello world");
18     }
19 
20 }

TestDI

package com.zyk.ioc;
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDI {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService=(UserService) applicationContext.getBean("userService");
        userService.say();
    }

}

applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         http://www.springframework.org/schema/beans/spring-beans.xsd">
 6 <bean id="userDao" class="com.zyk.ioc.UserDaoImpl"></bean>
 7 <bean id="userService" class="com.zyk.ioc.UserServiceImpl">
 8 <property name="userDao" ref="userDao"></property>
 9 </bean>
10 
11 </beans>

执行截图:

SSM学习02依赖注入的实现方式

用property标签作用:将id为UserDao的bean实例注入到userService中。

 

上一篇:Spring的IOC注解开发入门1


下一篇:Spring配置之标签的三两事