Spring:IOC容器的依赖注入(DI)之使用配置类代替beans.xml文件

郎家岭伯爵 2022年01月24日 405次浏览

前言

关于IOC容器的依赖注入之前已写过三篇博文:

而本文意在使用配置类进行开发,完全取代beans.xml文件

实现

导入dependency依赖

导入 spring-context 依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.13</version>
</dependency>

导入 Junit 依赖:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.1</version>
    <scope>test</scope>
</dependency>

创建pojo

创建一个User类,并赋值

package com.langjialing.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class User {
    @Value("langjialing")
    private String name;

    public String getName() {
        return name;
    }

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

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

User.java

配置类

注:

  • 配置类也会被Spring容器托管,注册到容器中。因为它本身就是一个@Component,通过@Configuration注解实现。
  • @Configuration代表这是一个配置类,与此前的beans.xml文件的功能是一致的。
  • @ComponentScan("com.langjialing.pojo") :指定扫描包的路径。
  • @Import(MyConfig2.class) : 当存在多个配置类时,相互引入配置类。
  • @Bean : 相当于bean.xml文件中的bean标签,方法的名字相当于bean标签的id属性,方法的返回值相当于bean标签的class属性。
  • return new User(); :返回要注入到bean中的对象。
package com.langjialing.config;

import com.langjialing.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
//@Configuration也会被Spring容器托管,注册到容器中。因为它本身就是一个@Component
//@Configuration代表这是一个配置类,与此前的beans.xml文件的功能是一致的
@ComponentScan("com.langjialing.pojo") //扫描包
@Import(MyConfig2.class) //存在多个配置类时,相互引入配置类
public class MyConfig {

    @Bean
    //相当于bean.xml文件中的bean标签,方法的名字相当于bean标签的id属性,方法的返回值相当于bean标签的class属性
    public User getUser(){
        return new User(); //返回要注入到bean中的对象
    }
}

配置类

测试类

注:

  • 如果完全使用配置类的方式来注入bean,就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载。
import com.langjialing.config.MyConfig;
import com.langjialing.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    @Test
    public void user(){
        // 如果完全使用配置类的方式来注入bean,就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = context.getBean("getUser", User.class);
        System.out.println(getUser);
    }
}

测试通过

目录结构

目录结构

赞助页面示例