spring学习(一)

依赖注入(DI)
1.项目结构
项目结构.png

2.java文件
UserDao.java

package DI;

public interface UserDao { //定义接口类UserDao
    public void save();  //定义UserDao的save方法
}

UserDaoImpl.java

package DI;

public class UserDaoImpl implements UserDao{ //定义UserDao的实现类,继承UserDao

    @Override
    public void save() {  //实现UserDao接口的方法
        System.out.println("UserDao save ....");
        
    }
    
}

UserService.java

package DI;

public interface UserService { //定义UserService接口
    public void save(); //定义UserService的save方法

}

UserServiceImpl.java

package DI;

public class UserServiceImpl implements UserService{ //定义UserService的实现类,继承UserService

    private UserDao userDao; //定义私有UserDao的私有对象(所有子类都能向父类转型)
    public void setUserDao(UserDao userDao){ //实现依赖注入的方法
        this.userDao = userDao; 
    }
    @Override
    public void save() {
        this.userDao.save(); //调用UserDaoImpl的save方法
        System.out.println("UserService save..."); 
        
    }

}

3.xml文件
applicationContext.xml

<?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">
<bean id = "userDao" class = "DI.UserDaoImpl"></bean> 
 
<bean id = "userService" class = "DI.UserServiceImpl">
    <property name="userDao" ref="userDao"/>
</bean>

</beans>

xml注解:在spring中,我们不再自己new对象,而是交给spring来管理。property属性为set类的方法,ref为注入对象。这里我们将id为userDao的对象注入到setUserDao的方法中。

Last modification:April 3rd, 2019 at 11:51 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment