Spring依赖注入

引言

Spring最核心的可以说是依赖注入,本文将详细阐述bean注入的两大方法

基于 XML 配置 

1. 检查 Bean 定义

在 applicationContext.xml 文件中,设置我们想要注入的 Bean 定义。通常,一个 Bean 定义的格式如下:


    
    
    

在上述示例中,id 属性指定了 Bean 的名称为 student,class 属性指定了该 Bean 对应的 Java 类的全限定名。

2. 确保配置文件被加载

要保证 applicationContext.xml 文件被正确加载到 Spring 应用上下文中。在 Java 代码中加载该配置文件的示例如下:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        // 加载 applicationContext.xml 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取 Bean
        Object student = context.getBean("student");
        System.out.println(student.toString());
    }
}

在上述代码中,使用 ClassPathXmlApplicationContext 加载 applicationContext.xml 文件,然后通过 getBean 方法尝试获取 rakutenCpsHttpICrmHandler Bean。如果 Bean 定义正确且配置文件被正确加载,就可以成功获取该 Bean

基于 Java 注解        

也就是 @Configuration注解,它的作用是定义这个类是用来定义bean的构造方法的

1. 检查 @Configuration 类中的 Bean 定义

创建一个带有 @Configuration 注解的类,并在其中使用 @Bean 注解定义 rakutenCpsHttpICrmHandler Bean。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public Student student () {
        // 创建并返回 Bean 实例
        return new Student ();
    }
}

2. 确保配置类被扫描

要确保包含 @Configuration 注解的类被 Spring 扫描到。可以使用 AnnotationConfigApplicationContext 来加载配置类

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        // 加载配置类
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        // 获取 Bean
        Student student= context.getBean(Student.class);
        System.out.println(student);
    }
}

     使用 AnnotationConfigApplicationContext 加载 AppConfig 配置类,然后通过 getBean 方法尝试获取 student Bean。如果配置类被正确扫描且 Bean 定义正确,就可以成功获取该 Bean

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