在 spring 框架中,bean 是一个非常核心的概念。简单来说,bean 是 spring 容器管理的对象,它是由 spring 容器实例化、配置和管理的。spring 通过依赖注入(di)将这些 bean 组合在一起,形成一个完整的应用程序。
什么是 bean?
bean 是 spring 框架中的一个基本单元,通常是一个普通的 java 对象(pojo),但它被 spring 容器管理。spring 容器负责 bean 的生命周期,包括创建、初始化、依赖注入、销毁等。
bean 的特点
实例化:
- spring 容器负责创建 bean 的实例。
- 可以通过配置文件(xml)、注解(如
@component、@service、@controller、@repository)或 java 配置类来定义 bean。
依赖注入:
- spring 容器会自动注入 bean 所需的依赖关系。
- 依赖注入可以通过构造器注入(constructor injection)或 setter 方法注入(setter injection)来实现。
生命周期管理:
- spring 容器管理 bean 的生命周期,包括初始化、使用和销毁。
- 可以通过实现
initializingbean接口或定义@postconstruct注解的方法来定义初始化逻辑。 - 可以通过实现
disposablebean接口或定义@predestroy注解的方法来定义销毁逻辑。
作用域:
- bean 可以有不同的作用域,如
singleton(单例)、prototype(原型)、request(请求)、session(会话)等。 - 默认情况下,bean 的作用域是
singleton,即容器中只有一个实例。
基础配置

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--name:为bean指定别名,别名可以有多个,使用逗号,分号,空格进行分隔-->
<bean id="bookservice" name="service service4 bookebi" class="com.itheima.service.impl.bookserviceimpl">
<property name="bookdao" ref="bookdao"/>
</bean>别名配置

作用范围
默认创建为单例对象 scope 默认 singleton
运行如下代码
package com.itheima;
import com.itheima.dao.bookdao;
import com.itheima.service.bookservice;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
public class appforscope {
public static void main(string[] args) {
applicationcontext ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
bookdao bookdao1 = (bookdao) ctx.getbean("bookdao");
bookdao bookdao2 = (bookdao) ctx.getbean("bookdao");
system.out.println(bookdao1);
system.out.println(bookdao2);
}
}输出如下:

这时应在bean对象配置里加入参数scope。
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--name:为bean指定别名,别名可以有多个,使用逗号,分号,空格进行分隔-->
<bean id="bookservice" name="service service4 bookebi" class="com.itheima.service.impl.bookserviceimpl">
<property name="bookdao" ref="bookdao"/>
</bean>
<!--scope:为bean设置作用范围,可选值为单例singloton,非单例prototype-->
<bean id="bookdao" name="dao" class="com.itheima.dao.impl.bookdaoimpl" scope="prototype" />
</beans>

到此这篇关于ssm spring bean基础配置的文章就介绍到这了,更多相关ssm spring bean配置内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论