Spring - Bean的概念及其基础配置

时间:2023-03-09 18:53:55
Spring - Bean的概念及其基础配置
概述

bean说白了就是一个普通的java类的实例,我们在bean中写一些我们的业务逻辑,这些实例由Sping IoC容器管理着。在web工程中的spring配置文件中,我们用<bean/>标签来配置一个bean。

Bean ID

没个bean都有至少一个ID,而且区别于其他bean的ID。在配置文件中,我们可以用 id 或者 name 来指定bean的ID。id属性只能设置一个值,如果项目中需要给bean指定多个ID,可以在name属性中设置多个,表示这个bean的别名。如果 id 和 name 属性都没有指定,Spring会在初始化bean的时候自动给bean赋一个唯一的ID(格式为:类的全路径@数字串)。但如果你的bean需要引用另外一个bean,那么被引用的那个bean就必须设置id或者name属性。当然我们还可以以内置bean的方式配置而不需要给内部bean指定ID。

除了在bean配置内部指定bean的ID,还可以用<alias/>标签来指定bean的别名:
<span style="font-size:14px;"><alias name="oldName" alias="newName1"/>
<alias name="oldName" alias="newName2"/></span>

Bean实例化的方式

Spring提供多种配置方式以实现不同方式来实例化一个bean

1. 通过默认构造函数
配置方式如下:
<span style="font-size:14px;"><bean id="exampleBean" class="examples.ExampleBean"/>

<bean name="anotherExample" class="examples.ExampleBeanTwo"/></span>
注意class中必须是一个类名,不能是接口。因为Spring是通过Class.newInstance方法来实例化的。

2. 通过类内部静态工厂方法
配置方式如下:
<span style="font-size:14px;"><bean id="clientService"
class="examples.ClientService"
factory-method="createInstance"/>
</span>
<span style="font-size:14px;">public class ClientService {
private static ClientService clientService = new ClientService();
private ClientService() {} public static ClientService createInstance() {
return clientService;
}
}</span>
这种方式在Spring是通过调用bean中factory-method中指定的静态方法来实例化这个bean。

3. 通过实例工厂类方法
配置方式如下:
<span style="font-size:14px;"><bean id="serviceLocator" class="examples.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean --></bean> <bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/> <bean id="accountService"
factory-bean="serviceLocator"
factory-method="createAccountServiceInstance"/></span>
<span style="font-size:14px;">public class DefaultServiceLocator {
private static ClientService clientService = new ClientServiceImpl();
private static AccountService accountService = new AccountServiceImpl(); private DefaultServiceLocator() {} public ClientService createClientServiceInstance() {
return clientService;
} public AccountService createAccountServiceInstance() {
return accountService;
}
}
</span>

这种方式Spring先加载实例工厂类DefaultServiceLocator,然后后面需要从这个类获取指定类实例的,只需要通过factory-bean和factory-method配置指定工厂类和调用方法即可。