📜  Bean和依赖注入(1)

📅  最后修改于: 2023-12-03 14:39:30.297000             🧑  作者: Mango

Bean和依赖注入

什么是Bean?

在Spring框架中,一个Bean就是一个需要被Spring容器管理的对象。这个对象可以是任何类的实例,包括用户定义的类、第三方类库中的类,甚至是Java SE API中的类。

Bean一般具有以下特点:

  • 生命周期由Spring容器管理
  • 可以被声明为单例模式或原型模式
  • 可以通过依赖注入获得其他Bean的实例
定义一个Bean

在Spring中,可以使用XML、Java和注解三种方式声明一个Bean。下面是一个简单的示例:

<bean id="person" class="com.example.Person">
    <property name="name" value="John" />
    <property name="age" value="25" />
</bean>

上面的代码定义了一个名为"person"的Bean,这个Bean是一个由com.example.Person类创建的实例,其中name和age属性被设置为"John"和25。

获取一个Bean

Spring容器可以让我们轻松地获取一个Bean的实例。我们可以通过ApplicationContext的getBean方法来获取一个Bean:

ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Person person = context.getBean("person", Person.class);

上面的代码中,我们通过ClassPathXmlApplicationContext加载了一个名为"application-context.xml"的XML文件,之后使用getBean方法获取了一个名为"person"的Bean,并将其转换为一个Person类的实例。

什么是依赖注入?

依赖注入(DI)是一种设计模式,目的是减少对象间的耦合。依赖注入是指将一个对象所依赖的其他对象由容器自动注入,而不是在该对象内部通过new关键字手动创建。依赖注入可以使代码更加模块化、可测试、可维护。

依赖注入的方式

在Spring中,有以下几种方式实现依赖注入:

  • 构造函数注入
  • setter方法注入
  • 字段注入
  • 接口注入

构造函数注入

构造函数注入是指在创建一个对象时,通过调用该对象的构造函数并传入其他需要依赖的对象实例来完成依赖注入。

public class PersonServiceImpl implements PersonService {
    private final PersonRepository personRepository;
    
    public PersonServiceImpl(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }
    
    // ...
}

上面的代码中,PersonServiceImpl类的构造函数接受一个PersonRepository实例作为参数并将其保存到成员变量中。

setter方法注入

setter方法注入是指在创建一个对象之后,通过调用该对象的setter方法来设置需要依赖的其他对象实例。

public class PersonServiceImpl implements PersonService {
    private PersonRepository personRepository;
    
    public void setPersonRepository(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }
    
    // ...
}

上面的代码中,PersonServiceImpl类定义了一个名为setPersonRepository的setter方法用于设置PersonRepository实例。

字段注入

字段注入是指在创建一个对象之后,直接将依赖的其他对象实例注入到对象的字段上。

public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonRepository personRepository;
    
    // ...
}

上面的代码中,PersonServiceImpl类使用@Autowired注解将一个PersonRepository实例自动注入到成员变量personRepository中。

接口注入

接口注入是指在创建一个对象时,通过调用该对象所实现的接口中的方法来完成依赖注入。

public interface PersonService {
    void setPersonRepository(PersonRepository personRepository);
}

public class PersonServiceImpl implements PersonService {
    private PersonRepository personRepository;
    
    @Override
    public void setPersonRepository(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }
    
    // ...
}

上面的代码中,PersonServiceImpl类实现了PersonService接口,并且通过重写setPersonRepository方法完成了依赖注入。

依赖注入的优点

依赖注入可以带来以下几个优点:

  • 减少对象间的耦合度,提高代码的模块化程度
  • 方便进行单元测试,因为可以通过Mockito等框架来模拟依赖对象
  • 提高代码的可维护性,因为依赖关系被明确地表述出来,修改某个依赖关系时可以更快地找到和修改相关代码

以上就是Bean和依赖注入的一些介绍。通过使用Bean和依赖注入,我们可以使我们的代码更加模块化、可测试、可维护。