推荐学习:《java视频教程》
spring 框架作为一个管理 bean 的 ioc 容器,那么 bean 自然是 spring 中的重要资源了,那 bean 的作用域是什么意思?又有几种类型呢?接下来我们一起来看。
ps:java 中的公共类可称之为 bean 或 java bean。
1.作用域bean 的作用域是指 bean 在 spring 整个框架中的某种行为模式。比如 singleton 单例作用域,就表示 bean 在整个 spring 中只有一份,它是全局共享的,当有人修改了这个值之后,那么另一个人读取到的就是被修改后的值。
举个例子,比如我们在 spring 中定义了一个单例的 bean 对象 user(默认作用域为单例),具体实现代码如下:
@componentpublic class userbean { @bean public user user() { user user = new user(); user.setid(1); user.setname("java"); // 此行为重点:用户名称为 java return user; }}
然后,在 a 类中使用并修改了 user 对象,具体实现代码如下:
@controllerpublic class acontroller { @autowired private user user; public user getuser() { user user = user; user.setname("mysql"); // 此行为重点:将 user 名称修改了 return user; }}
最后,在 b 类中也使用了 user 对象,具体实现代码如下:
@controllerpublic class bcontroller { @autowired private user user; public user getuser() { user user = user; return user; }}
此时我们访问 b 对象中的 getuser 方法,就会发现此时的用户名为 a 类中修改的“mysql”,而非原来的“java”,这就说明 bean 对象 user 默认就是单例的作用域。如果有任何地方修改了这个单例对象,那么其他类再调用就会得到一个修改后的值。
2.作用域分类在 spring 中,bean 的常见作用域有以下 5 种:
singleton:单例作用域;prototype:原型作用域(多例作用域);request:请求作用域;session:会话作用域;application:全局作用域。注意:后 3 种作用域,只适用于 spring mvc 框架。
2.1 singleton官方说明:(default) scopes a single bean definition to a single object instance for each spring ioc container.
描述:该作用域下的 bean 在 ioc 容器中只存在一个实例:获取 bean(即通过 applicationcontext.getbean等方法获取)及装配 bean(即通过 @autowired 注入)都是同一个对象。
场景:通常无状态的 bean 使用该作用域。无状态表示 bean 对象的属性状态不需要更新。
备注:spring 默认选择该作用域。
2.2 prototype官方说明:scopes a single bean definition to any number of object instances.
描述:每次对该作用域下的 bean 的请求都会创建新的实例:获取 bean(即通过 applicationcontext.getbean 等方法获取)及装配 bean(即通过 @autowired 注入)都是新的对象实例。
场景:通常有状态的 bean 使用该作用域。
2.3 request官方说明:scopes a single bean definition to the lifecycle of a single http request. that is, each http request has its own instance of a bean created off the back of a single bean definition. only valid in the context of a web-aware spring applicationcontext.
描述:每次 http 请求会创建新的 bean 实例,类似于 prototype。
场景:一次 http 的请求和响应的共享 bean。
备注:限定 spring mvc 框架中使用。
2.4 session官方说明:scopes a single bean definition to the lifecycle of an http session. only valid in the context of a web-aware spring applicationcontext.
描述:在一个 http session 中,定义一个 bean 实例。
场景:用户会话的共享 bean, 比如:记录一个用户的登陆信息。
备注:限定 spring mvc 框架中使用。
2.5 application官方说明:scopes a single bean definition to the lifecycle of a servletcontext. only valid in the context of a web-aware spring applicationcontext.
描述:在一个 http servlet context 中,定义一个 bean 实例。
场景:web 应用的上下文信息,比如:记录一个应用的共享信息。
备注:限定 spring mvc 框架中使用。
3.作用域设置我们可以通过 @scope 注解来设置 bean 的作用域,它的设置方式有以下两种:
直接设置作用域的具体值,如:@scope(prototype);
设置 configurablebeanfactory 和 webapplicationcontext 提供的 scope_xxx 变量,如 @scope(configurablebeanfactory.scope_prototype)。
具体设置代码如下:
bean 的作用域是指 bean 在 spring 整个框架中的某种行为模式。bean 的常见作用域有 5 种:singleton(单例作用域)、prototype(原型作用域)、request(请求作用域)、session(请求作用域)、application(全局作用域),注意后 3 种作用域只适用于 spring mvc 框架。
推荐学习:《java视频教程》
以上就是java详细解析之bean作用域的详细内容。