bean 基础配置

IoC 概念:2. IoC 控制反转

bean 基础配置

bean 别名

可以通过配置 name 属性配置 bean 的别名

  • name 属性中的别名可以配置多个,可以通过 空格、分号、逗号 进行分割。
  • name 属性中配置的别名的使用范围
    1. 可以在 property 中的 ref 中指定
    2. 可以在 ctx.getBean 中指定

applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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">

<bean id="bookDao" name="dao" class="cn.pangcy.dao.impl.BookDaoImpl" />
<!-- 指定多个别名 -->
<bean id="bookService" name="service bookService bookEbi" class="cn.pangcy.service.impl.BookServiceImpl">
<!-- ref 中指向 name 的别名 -->
<property name="bookDao" ref="dao"/>
</bean>
</beans>

App 启动类

1
2
3
4
5
6
7
8
9
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// 在 getBean 中指定 name 别名
BookService bookService = (BookService) ctx.getBean("service");
bookService.save();
}
}

记录一个异常

如果出现了 NoSuchBeanDefinitionException,则说明没有找到这个 bean 的声明 No bean named ‘service1’ available 则说明了在 ctx.getBean 时具体哪一个 bean 没有找到

出现的原因是:getBean 时无论是通过 id 还是 name 获取,如果都无法获取到,则会抛出该异常

bean 的作用范围

Spring 中,bean 默认是通过单例模式创建的,即通过 getBean 获取多个对象都是同一个对象。

可以通过在 bean 中配置 scope="prototype",改为每次获取都是创建都是一个新的对象

验证是否是单例模式

bookService1 == bookService2 说明引用的是同一个对象

1
2
3
4
5
6
7
8
9
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

BookService bookService1 = (BookService) ctx.getBean("bookService");
BookService bookService2 = (BookService) ctx.getBean("bookService");
System.out.println(bookService2 == bookService1); // ---> true
}
}

修改 bean 的作用域范围为: prototype

  • bean 默认是单例模式:singleton
  • scope 属性定义了 bean 的作用范围

配置后再次验证 bookService1 == bookService2 会返回 false

1
2
3
4
5
6
7
8
9
10
<?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">
<bean id="bookDao" name="dao" class="cn.pangcy.dao.impl.BookDaoImpl" />
<!-- 配置 scope 属性为 prototype -->
<bean id="bookService" class="cn.pangcy.service.impl.BookServiceImpl" scope="prototype">
<property name="bookDao" ref="dao"/>
</bean>
</beans>

bean 基础配置
https://blog.pangcy.cn/2023/04/02/后端编程相关/java/spring/bean 基础配置/
作者
子洋
发布于
2023年4月2日
许可协议