在项目的 pom.xml 中添加 Spring 框架的支持,xml 配置如下:
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.2.8.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>5.2.8.RELEASEversion>
dependency>
dependencies>
从上述配置中可以看出,添加的框架有 spring-context:spring 上下⽂,还有 spring-beans:管理对象的模块。
在创建好的项目的java文件夹下创建一个启动类,包含main方法即可:
public class App {
public static void main(String[] args) {
}
}
Bean就是Java中一个普通的对象
public class User {
public String sayHello(String name) {
return name + "Hello World!";
}
}
<beans>
<bean id="user" class="com.fyd.User"></bean>
</beans>
因为对象都交给 Spring 管理了,所以获取对象要从 Spring 中获取,那么就得先得到 Spring 的上下文。
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
BeanFactory context =
new ClassPathXmlApplicationContext("spring-config.xml");
ApplicationContext 与 BeanFactory
- 继承关系和功能⽅⾯来说:Spring 容器有两个顶级的接⼝:BeanFactory 和 ApplicationContext。其中 BeanFactory 提供了基础的访问容器的能⼒,⽽ ApplicationContext 属于 BeanFactory 的⼦类,它除了继承了 BeanFactory 的所有功能之外,它还拥有独特的特性,还添加了对国际化⽀持、资源访问⽀持、以及事件传播等⽅⾯的⽀持。
- 从性能⽅⾯来说:ApplicationContext 是⼀次性加载并初始化所有的 Bean 对象,⽽
BeanFactory 是需要那个才去加载那个,因此更加轻量。
从 spring 中获取 bean 对象
User user = (User) context.getBean("user");
System.out.println(user.sayHello("Spring"));
getBean()
方法是 Spring 框架中的一个重要方法,用于从 Spring 容器(应用程序上下文)中获取指定名称或类型的 bean 实例。它可以通过 bean 的名称或类型来获取对应的 bean 对象。下面是 getBean()
方法的用法示例:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 通过 bean 的名称获取 bean 实例
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorldBean");
在这个示例中,假设存在一个名为 “helloWorldBean” 的 bean 定义,通过指定名称来获取相应的 bean 实例。
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 通过 bean 的类型获取 bean 实例
HelloWorld helloWorld = context.getBean(HelloWorld.class);
在这个示例中,假设 HelloWorld 类是一个在 Spring 上下文中定义的 bean,通过指定类型来获取相应的 bean 实例。
注意事项:
getBean()
方法将抛出 NoSuchBeanDefinitionException
异常。getBean()
方法将抛出 NoUniqueBeanDefinitionException
异常。除了基本用法,getBean()
方法还有其他变体,可以传递参数、指定作用域等。具体的用法取决于你的项目需求和 Spring 配置。在 Spring Boot 中,通常会使用注解来自动装配 bean,而不必显式调用 getBean()
方法。
另外,在现代的 Spring 版本中,建议尽量避免直接使用 getBean()
方法,而是使用自动装配(Autowired)等更便捷的方式来获取 bean。这样可以更好地利用 Spring 框架的依赖注入机制。