DI的几种注入方式

发布于:2022-11-09 ⋅ 阅读:(9) ⋅ 点赞:(0) ⋅ 评论:(0)

前言: 时间有限,课程赶得太紧,明天还要学习新的内容,这是我参考网上的教程,写的很粗糙,可能不便于阅读,后期再做完善吧┭┮﹏┭┮

1.setter注入以及简单数据类型注入

1.环境准备

image-20221109221055860

创建接口和实现类BookDao、BookDaoImpl、UserDao、UserDaoImpl、BookService、BookServiceImpl

package com.hnu.dao;
//先创建接口,然后创建实现类,最后在App类中引用实现
public interface BookDao {
    public void save();
}



package com.hnu.dao.impl;
import com.hnu.dao.BookDao;
//实现接口
public class BookDaoImpl implements BookDao {
    private String databaseName;
    private int connectionNum;
    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }
    public void setConnectionNum(int connectionNum) {
        this.connectionNum = connectionNum;
    }
    public void save() {
        System.out.println("book dao save " + databaseName + "  " + connectionNum);
    }
}



package com.hnu.dao;
public interface UserDao {
    public void save();
}




package com.hnu.dao.impl;
import com.hnu.dao.UserDao;
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("user dao save ...");
    }
}




package com.hnu.service;
public interface BookService {
    public void save();
}






package com.hnu.service.impl;
import com.hnu.dao.BookDao;
import com.hnu.dao.UserDao;
import com.hnu.service.BookService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class BookServiceImpl implements BookService {
    //在这个实现类中也可以创建bookDao接口的对象,在接口中是不能创建对象的,接口中存放的是方法
    private BookDao bookDao;
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
    public void save() {
        System.out.println("book service save ...");
        bookDao.save();
        userDao.save();
    }
}

2.声明属性并提供setter方法

3.配置文件中进行注入配置

<?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="bookDao" class="com.hnu.dao.impl.BookDaoImpl">
        <!---注入简单数据类型->
        <property name="connectionNum" value="6"/>
        <property name="databaseName" value="pgsql"/>
    </bean>
    <bean id="useDao" class="com.hnu.dao.impl.UserDaoImpl"/>

    <bean id="bookService" class="com.hnu.service.impl.BookServiceImpl">
        <!--配置property-->
        <!--通过name找到setter方法,把首字母大写前面加上set  这种方式存在一定的耦合性-->
        <!--ref里面发个上面的id-->
        <property name="bookDao" ref="bookDao"/>
        <property name="userDao" ref="useDao"/>
    </bean>
</beans>

4.运行程序

AppForDISet

package com.hnu;

import com.hnu.service.BookService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppForDISet {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService)ctx.getBean("bookService");
        bookService.save();
        //ctx.close();
        ctx.registerShutdownHook();
    }
}

image-20221109221530442

2.构造器注入引用数据类型和简单数据类型

1.环境准备

image-20221109222010084

创建相应的接口和实现类BookDao、BookDaoImpl、UserDao、UserDaoImpl、BookService、BookServiceImpl

package com.hnu.dao;
//先创建接口,然后创建实现类,最后在App类中引用实现
public interface BookDao {
    public void save();
}




package com.hnu.dao.impl;
import com.hnu.dao.BookDao;
//实现接口
public class BookDaoImpl implements BookDao {
    private String databaseName;
    private int connectionNum;

    public BookDaoImpl(String databaseName, int connectionNum) {
        this.databaseName = databaseName;
        this.connectionNum = connectionNum;
    }
    public void save() {
        System.out.println("book dao save " + databaseName + "  " + connectionNum);
    }
}




package com.hnu.dao;
public interface UserDao {
    public void save();
}



package com.hnu.dao.impl;
import com.hnu.dao.UserDao;
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("user dao save ...");
    }
}




package com.hnu.service;
public interface BookService {
    public void save();
}





package com.hnu.service.impl;
import com.hnu.dao.BookDao;
import com.hnu.dao.UserDao;
import com.hnu.service.BookService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BookServiceImpl implements BookService {
    //在这个实现类中也可以创建bookDao接口的对象,在接口中是不能创建对象的,接口中存放的是方法
    private BookDao bookDao;
    private UserDao userDao;
    public BookServiceImpl(BookDao bookDao, UserDao userDao) {
        this.bookDao = bookDao;
        this.userDao = userDao;
    }
    public void save() {
        System.out.println("book service save ...");
        bookDao.save();
        userDao.save();
    }
}

2.注入引用数据类型和简单数据类型

3.配置文件中进行注入配置

<?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="bookDao" class="com.hnu.dao.impl.BookDaoImpl">
        <!--注入简单数据类型-->
        <!--方式一,通过名字注入-->
<!--        <constructor-arg name="databaseName" value="pgsql"/>
        <constructor-arg name="connectionNum" value="6"/>-->
        <!--方式二:通过类型传入,但存在一个问题,当两个都是String类型或者int的话就会矛盾报错-->
<!--        <constructor-arg type="java.lang.String" value="pgsql"/>
        <constructor-arg type="int" value="6"/>-->
        <!--方式三:按照索引下标注入,下标从0开始-->
        <!--这种方式可以解决参数类型重复问题,但是如果构造方法参数顺序发生变化后,这种方式又带来了耦合问题-->
        <constructor-arg index="0" value="pgsql"/>
        <constructor-arg index="1" value="6"/>
    </bean>
    <bean id="userDao" class="com.hnu.dao.impl.UserDaoImpl"/>

    <!--通过构造注入-->
    <!--name 构造中参数名字一样-->
    <bean id="bookService" class="com.hnu.service.impl.BookServiceImpl">
        <constructor-arg name="bookDao" ref="bookDao"/>
        <constructor-arg name="userDao" ref="userDao"/>
    </bean>

</beans>

4.运行程序

AppForDIConstructor

package com.hnu;

import com.hnu.service.BookService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppForDIConstructor {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService)ctx.getBean("bookService");
        bookService.save();
        //ctx.close();
        ctx.registerShutdownHook();
    }
}

image-20221109222336882

3.自动配置

5.3.2 自动装配方式有哪些?

  • 按类型(常用)
  • 按名称
  • 按构造方法
  • 不启用自动装配

1.准备环境

image-20221109222733606

创建接口和实现类BookDao、BookDaoImpl、UserDao、UserDaoImpl、BookService、BookServiceImpl

package com.hnu.dao;

//先创建接口,然后创建实现类,最后在App类中引用实现
public interface BookDao {
    public void save();
}






package com.hnu.dao.impl;
import com.hnu.dao.BookDao;
//实现接口
public class BookDaoImpl implements BookDao {
    private String databaseName;
    private int connectionNum;

    public BookDaoImpl(String databaseName, int connectionNum) {
        this.databaseName = databaseName;
        this.connectionNum = connectionNum;
    }
    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }
    public void setConnectionNum(int connectionNum) {
        this.connectionNum = connectionNum;
    }
    public void save() {
        System.out.println("book dao save " + databaseName + "  " + connectionNum);
    }
}




package com.hnu.dao;
public interface UserDao {
    public void save();
}





package com.hnu.dao.impl;
import com.hnu.dao.UserDao;
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("user dao save ...");
    }
}



package com.hnu.service;
public interface BookService {
    public void save();
}




package com.hnu.service.impl;
import com.hnu.dao.BookDao;
import com.hnu.dao.UserDao;
import com.hnu.service.BookService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BookServiceImpl implements BookService {
    //在这个实现类中也可以创建bookDao接口的对象,在接口中是不能创建对象的,接口中存放的是方法
    private BookDao bookDao;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
    public void save() {
        System.out.println("book service save ...");
        bookDao.save();
    }
}

2.引用数据类型和简单数据类型的自动注入bytype

3.完成自动配置的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 class="com.hnu.dao.impl.BookDaoImpl">
        <constructor-arg index="0" value="pgsql"/>
        <constructor-arg index="1" value="6"/>
    </bean>
    <bean class="com.hnu.dao.impl.UserDaoImpl"/>

    <bean id="bookService" class="com.hnu.service.impl.BookServiceImpl" autowire="byType"/>
</beans>

3.运行程序

AppForDIAutoSet

package com.hnu;

import com.hnu.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppForDIAutoSet {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService)ctx.getBean("bookService");
        bookService.save();
    }
}

运行结果:

image-20221109223130776

4.集合注入

环境准备

image-20221109223336304

创建接口和实现类BookDao、BookDaoImpl

package com.hnu.dao;
//先创建接口,然后创建实现类,最后在App类中引用实现
public interface BookDao {
    public void save();
}





package com.hnu.dao.impl;
import com.hnu.dao.BookDao;
import java.util.*;
//实现接口
public class BookDaoImpl implements BookDao {
    private int[] array;

    private List<String> list;

    private Set<String> set;

    private Map<String, String> map;

    private Properties properties;

    public void setArray(int[] array) {
        this.array = array;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void save() {
        System.out.println("book dao save ...");

        System.out.println("遍历数组:" + Arrays.toString(array));

        System.out.println("遍历List" + list);

        System.out.println("遍历Set" + set);

        System.out.println("遍历Map" + map);

        System.out.println("遍历Properties" + properties);

    }
}

2.引入spring依赖

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.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="bookDao" class="com.hnu.dao.impl.BookDaoImpl">
        <property name="array">
            <!--注入数组类型数据-->
            <array>
                <value>100</value>
                <value>200</value>
                <value>300</value>
            </array>
        </property>

        <property name="list">
            <!--注入List类型数据-->
            <list>
                <value>htu</value>
                <value>hnu</value>
                <value>mukewang</value>
                <value>bokeyuan</value>
            </list>
        </property>

        <property name="set">
            <!--注入Set类型数据-->
            <set>
                <value>htu</value>
                <value>hnu</value>
                <value>mukewang</value>
                <value>bokeyuan</value>
            </set>
        </property>

        <property name="map">
            <!--注入Map类型数据-->
            <map>
                <entry key="country" value="china"/>
                <entry key="province" value="henan"/>
                <entry key="city" value="kaifeng"/>
            </map>
        </property>

        <property name="properties">
            <!--注入Properties类型数据-->
            <props>
                <prop key="country">china</prop>
                <prop key="province">henan</prop>
                <prop key="city">kaifeng</prop>
            </props>
        </property>
    </bean>
</beans>

4.运行程序AppForDICollection

package com.hnu;

import com.hnu.dao.BookDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppForDICollection {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookDao bookDao = (BookDao)ctx.getBean("bookDao");
        bookDao.save();
    }
}

运行结果:

image-20221109224249737