spring依赖注入的4种方式

Spring 依赖注入的4种方式

spring依赖注入的4种方式_第1张图片

一、Set注入

必须要有setter方法

public class UserDao {
    public void test(){
        System.out.println("=====test======");
    }
}

package com.yao.service;

import com.yao.pojo.UserDao;

public class UserService {

    private UserDao userDao;


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

    public void test(){
        System.out.println("UserService.test");
    }
}

    <bean id="userDao" class="com.yao.pojo.UserDao"/>
    <bean id="userService" class="com.yao.service.UserService">
        <property name="userDao" ref="userDao"/>
    bean>

二、构造器注入

必须要有有参构造方法

package com.yao.service;

import com.yao.pojo.UserDao;

public class UserService {

    private UserDao userDao;
    
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public void test(){
        System.out.println("UserService.test");
    }
}
<bean id="userDao" class="com.yao.pojo.UserDao"/>
    <bean id="userService" class="com.yao.service.UserService">
        <constructor-arg index="0" name="userDao" ref="userDao"/>
bean>

三、静态工厂方法注入

package com.yao.factory;

import com.yao.pojo.UserDao;

public class Factory {

    public static UserDao getUserDao(){
        return new UserDao();
    }
}
    <bean id="userDao" class="com.yao.factory.Factory" factory-method="getUserDao"/>
    <bean id="userService" class="com.yao.service.UserService">
        <property name="userDao" ref="userDao"/>
    bean>

四、实例工厂方法注入

package com.yao.factory;

import com.yao.pojo.UserDao;

public class Factory {

//    静态工厂
    public static UserDao getUserDao(){
        return new UserDao();
    }

//    实例工厂
    public UserDao userDao(){
        return new UserDao();
    }
}
    <bean id="factory" class="com.yao.factory.Factory"/>
    <bean id="userDao2" factory-bean="factory" factory-method="userDao"/>
    <bean id="userService" class="com.yao.service.UserService">
        <property name="userDao" ref="userDao2">property>
    bean>

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