spring依赖注入

set方法
接口

public interface UserDao {
    public void save();
}

public interface UserService {
    public void save();
}

实现

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void save() {
        userDao.save();
    }
}
public class UserDaoImpl implements UserDao {
    public UserDaoImpl() {
        System.out.println("UserDaoImpl创建");
    }
    public void init(){
        System.out.println("初始化方法");
    }

    public void destory()
    {
        System.out.println("销毁方法");
    }
    public void save() {
        System.out.println("Spring");
    }
}

xml

 <bean id="userService" class="com.ruan.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>

p注入

   <bean id="userService" class="com.ruan.service.impl.UserServiceImpl" p:userDao-ref="userDao"/>

构造方法

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }


    @Override
    public void save() {
        userDao.save();
    }
}
    <bean id="userService" class="com.ruan.service.impl.UserServiceImpl">
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
    </bean>
上一篇:Spring控制反转的理解-IOC的理解


下一篇:Spring01:概述及IOC理论推导