bean依赖注入三种方式

bean依赖注入的三种方式如下:

  1. 构造方法注入
  2. set方法注入
  3. P命名空间注入

此处演示的项目结构如下:
bean依赖注入三种方式_第1张图片
方法一: 构造方法注入
UserDaoImpl.java

public class UserDaoImpl implements IUserDao {
    @Override
    public void save() {
        System.out.println("save方法执行成功...");
    }
}

UserServiceImpl.java

public class UserServiceImpl implements IUserService {
    
    private IUserDao userDao;
    
    public UserServiceImpl(IUserDao userDao) {
        this.userDao = userDao;
    }
    
    @Override
    public void save() {
        userDao.save();
    }
}

applicationContext.xml


<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"
       xmlns:p="http://www.springframework.org/schema/p">

    
    <bean id="userDao" class="com.hy.dao.impl.UserDaoImpl" />
    <bean id="userService" class="com.hy.service.impl.UserServiceImpl">
      <constructor-arg name="userDao" ref="userDao" />
    bean>

beans>

TestDependencyInjection.java

public class TestDependencyInjection {
    
    /**
     * 方式一、构造方法注入
     */
    @Test
    public void test1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        IUserService userService = (IUserService) applicationContext.getBean("userService");
        userService.save();
    }
}

输出结果
bean依赖注入三种方式_第2张图片

UserDao.java和TestDependencyInjection.java代码一致,下面的方法二和方法三省略此处

方法二、set方法注入
UserServiceImpl.java

public class UserServiceImpl implements IUserService {
    
    private IUserDao userDao;
    
    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }
    
    @Override
    public void save() {
        userDao.save();
    }
}

applicationContext.xml

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

其中property标签中的name属性值为UserServiceImplz类中的userDao字段
方法三:P命名空间注入(原理也是set方法注入)
applicationContext.xml首先引入P命名空间

xmlns:p="http://www.springframework.org/schema/p"

UserServiceImpl.java

public class UserServiceImpl implements IUserService {
    
    private IUserDao userDao;
    
    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }
    
    @Override
    public void save() {
        userDao.save();
    }
}

applicationContext.xml

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

详细代码地址如下:详细代码地址

你可能感兴趣的:(spring,spring)