【Spring】 依赖注入(DI)

h# 依赖注入(DI)

依赖注入(DI)

  • 依赖注入(Dependency Injection,DI)。
  • 依赖 : 指Bean对象的创建依赖于 容器 . Bean对象的依赖资源 .
  • 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .

构造器注入

我们在之前的案例4已经详细讲过了

  • 有参注入
  • 无参注入

set注入 (重点)

要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .

测试pojo类 :

Address.java

public class Address {

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Student.java

package com.demo.pojo;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Student {

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    public void show() {
        System.out.println("name=" + name
                           + ",address=" + address.getAddress()
                           + ",books="
                          );
        for (String book : books) {
            System.out.print("<<" + book + ">>\t");
        }
        System.out.println("\n爱好:" + hobbys);

        System.out.println("card:" + card);

        System.out.println("games:" + games);

        System.out.println("wife:" + wife);

        System.out.println("info:" + info);

    }
}

1、常量注入

<bean id="student" class="com.demo.pojo.Student">
  <property name="name" value="小明"/>
</bean>

测试:

@Test
public void test01(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    Student student = (Student) context.getBean("student");

    System.out.println(student.getName());

}

2、Bean注入

注意点:这里的值是一个引用,ref

<bean id="addr" class="com.demo.pojo.Address">
<property name="address" value="重庆"/>
</bean>

<bean id="student" class="com.demo.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
</bean>

3、数组注入

<bean id="student" class="com.demo.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
<property name="books">
<array>
<value>西游记</value>
<value>红楼梦</value>
<value>水浒传</value>
</array>
</property>
</bean>

4、List注入

<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>爬山</value>
</list>
</property>

5、Map注入

<property name="card">
<map>
<entry key="中国邮政" value="456456456465456"/>
<entry key="建设" value="1456682255511"/>
</map>
</property>

6、set注入

<property name="games">
    <set>
        <value>LOL</value>
        <value>BOB</value>
        <value>COC</value>
    </set>
</property>

7、Null注入

<property name="wife">
    <null/>
</property>

8、Properties注入

<property name="info">
    <props>
        <prop key="学号">20190604</prop>
        <prop key="性别"></prop>
        <prop key="姓名">小明</prop>
    </props>
</property>

测试结果:

拓展注入实现

User.java : 【注意:这里没有有参构造器!】

public class User {
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
        "name='" + name + '\'' +
        ", age=" + age +
        '}';
    }
}

1、P 命名空间注入 : 需要在头文件中假如约束文件

导入约束 :xmlns:p="http://www.springframework.org/schema/p"

properties属性注入 : 有构造方法时需要有 无参构造

scope属性 :

singleton 单例模式,Spring的默认机制 单线程使用

prototype 原型模式 每次从容器中get的时候都会生成一个新的对象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns="http://www.springframework.org/schema/beans"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans.xsd">

  <!--  p命名空间注入 properties属性注入 : 有构造方法时需要有 无参构造-->
  <!--	P(属性: properties)命名空间 , 属性依然要设置set方法-->
  <bean id="user" class="com.demo.pojo.User" p:age="18" p:name="zhang"/>
</beans>

2、c 命名空间注入 : 需要在头文件中假如约束文件

导入约束 : xmlns:c="http://www.springframework.org/schema/c"


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:c="http://www.springframework.org/schema/c"
  xmlns="http://www.springframework.org/schema/beans"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <!--  c标签注入 构造器注入:有参构造  多线程-->
  <!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
  <bean id="userR" class="com.demo.pojo.User" c:name="wang" c:age="18" scope="prototype"/>

</beans>

发现问题:没有写有参构造,使用构造器注入需要有有参构造

解决:把有参构造器加上,c标签(Constructor) 就是另类的一种构造器注入!

测试代码:

public class TestMain {

    public static void main(String[] args) {

        // beans注入
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        
        System.out.println( "姓名 " + student.getName());
        System.out.println("地址" +  student.getAddress().getAddress());
        System.out.println("getBooks"+Arrays.toString(student.getBooks()));
        System.out.println("getHobbys"+student.getHobbys());
        System.out.println("getCard"+student.getCard());
        System.out.println("getGames"+student.getGames());
        System.out.println("getWife"+student.getWife());
        System.out.println("getInfo"+student.getInfo());
        student.show();

    }
    @Test
    public void test01() {
        ApplicationContext context = new ClassPathXmlApplicationContext("userBean.xml");

        // scope = singleton
        User user = context.getBean("user", User.class);
        User user2 = context.getBean("user", User.class);
        // scope = prototype
        User userR = context.getBean("userR", User.class);
        User userR2 = context.getBean("userR", User.class);

        System.out.println("singleton:单例");
        System.out.println(user);
        System.out.println(user2);
        System.out.println(user == user2);

        System.out.println("prototype:原型");
        System.out.println(userR);
        System.out.println(userR2);
        System.out.println(userR == userR2);
    }

Bean的作用域

在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲,bean就是由IoC容器初始化、装配及管理的对象

Bean Scopes :: Spring Framework

几种作用域中,requestsession作用域仅在基于web的应用中使用(不必关心你所采用的是什么web应用框架),只能用在基于web的Spring ApplicationContext 环境。

Singleton 单例模式

当一个bean的作用域为singleton ,那么Spring IoC容器中只会存在一个共享的bean实例, 并且所有对bean的请求。只要id与该bean定义相匹配,则只会返回bean的同一实例。

Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。

要在XML中将bean定义成singleton,可以这样配置:

<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" >
<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">

测试:

@Test
public void test03(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user = (User) context.getBean("user");
    User user2 = (User) context.getBean("user");
    System.out.println(user==user2);
}
Prototype 原型模式

当一个bean的作用域为prototype表示一个bean定义对应多个对象实例

Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)都会创建一个新的bean实例

Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置:

<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>  
<!-- 错误案例,以前可以 -->
<!-- <bean id="account" class="com.foo.DefaultAccount" singleton="false"/> -->

其他几种模式:requestsessionapplicationwebsocket都是在web模式中才能使用。 Only valid in the context of a web-aware

Request 请求

当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例

即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>

针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。

当处理请求结束 request作用域的bean实例将被销毁。

Session 会话

当一个bean的作用域为session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前`HTTP Session**内有效**。

request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP 会话被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉

简单概括:application就是在全局中存在,session就是在session中存在,request就是在request中存在。当请求、会话、这个应用结束的时候,就会销毁。

Listener

监听器

Listener 是用于监听 Servlet 容器中某些特定事件(如请求的开始和结束,Session 的创建和销毁等)的组件。Spring 提供了一些内置的监听器,能够帮助你在应用的生命周期中执行特定的操作。

监听web

<web-app>
	...
	<listener>
		<listener-class>
			org.springframework.web.context.request.RequestContextListener
		</listener-class>
	</listener>
	...
</web-app>
  • RequestContextListener 是一个用于监听请求上下文的 Spring 监听器,它在每个 HTTP 请求的生命周期开始时初始化 Spring RequestContext。通过这个监听器,可以让 Spring 在每个请求中管理与请求相关的环境变量和资源。具体来说,它确保在每个请求线程中创建并管理 Spring 的 RequestContext
  • 它通常用于 Web 应用程序中,以便在每个请求过程中能够获取到如 Spring 的 Locale 或其他请求相关的信息。
过滤器

Filter 是用于拦截请求和响应的组件,在请求被分发给 Servlet 之前或响应被返回之前进行某些处理。可以用于日志记录、权限检查、数据压缩、请求和响应的修改等

监听其他 加一个过滤器

<web-app>
	...
	<filter>
		<filter-name>requestContextFilter</filter-name>
		<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>requestContextFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	...
</web-app>
  • RequestContextFilter 是 Spring 提供的一个过滤器,它与 RequestContextListener 类似,作用是在每个 HTTP 请求的生命周期中,为请求上下文提供支持。它保证在每个请求的线程中,Spring 的 RequestContext 能够正确地初始化,并且能够正确地传递给后续的 Servlet、Filter 或其他组件。
  • url-pattern="/*" 表示此过滤器会应用到所有 URL 路径,也就是所有的请求都会经过这个过滤器。你也可以根据需要配置更精确的路径模式(例如 /api/*)。
  • 过滤器的优先级会影响其执行顺序。一般来说,RequestContextFilter 被放在最前面,因为它需要确保请求上下文在其他组件之前已正确创建。
总结

通常放在 web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <!-- 其他配置 -->
</web-app>

  • 使用 RequestContextListener 监听器可以确保 Spring 的请求上下文在每个 HTTP 请求的生命周期内得到正确的初始化。
  • 使用 RequestContextFilter 过滤器也能达到类似目的,但它的优势在于可以在请求和响应的过程中进行更灵活的拦截和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨DaB

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值