Spring中获取bean的八种方式,你get了几种?

1、在初始化时保存ApplicationContext对象

适用于Spring框架的独立应用程序,须要程序通过配置文件初始化Spring。

applicationContext.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="test" class="com.sxtx.bean.Test">
</bean>

</beans>

代码:

@Test
public void test() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml"); 
    Test test= (Test) applicationContext.getBean("test");
    System.out.println(test);
}

2、通过Spring提供的工具类获取ApplicationContext对象

适合于Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。以下两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); 
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); 
ac1.getBean("beanId"); 
ac2.getBean("beanId");

3、实现接口ApplicationContextAware

Spring Boot应用程序中,你可以通过@Autowired注解、ApplicationContext或者@ComponentScan来查找或检查一个特定的Bean是否存在。以下是几种常见的方法: 1. **使用@Autowired注解**:如果你已经在其他地方声明并使用了@Autowired注解来自动装配某个bean,那么尝试注入它,如果Spring容器找不到,就会抛出异常,表明该bean不存在。 ```java @Autowired private YourBean yourBean; // 如果yourBean不存在,这里会抛出NullPointerException // 或者使用Optional @Autowired private Optional<YourBean> optionalBean; if (optionalBean.isPresent()) { YourBean yourBean = optionalBean.get(); } ``` 2. **使用ApplicationContext**:Spring ApplicationContext提供了一个getBean方法,可以显式地获取Bean。 ```java ApplicationContext context = SpringApplication.run(Application.class); YourBean yourBean = context.getBean(YourBean.class); // 如果bean不存在,返回null ``` 3. **@ComponentScan扫描**:如果你使用@ComponentScan来扫描包或组件,可以在扫描后直接通过类名来判断是否存在。 ```java @Configuration @ComponentScan(basePackages = "com.example") public class AppConfig { @PostConstruct public void checkBeanExistence() { if (AppConfigUtils.hasBean("yourBean")) { // 存在 } else { // 不存在 } } private static boolean hasBean(String beanName) { return ApplicationContext.getRequiredBean(beanName) != null; } } ``` 在这个例子中,`hasBean`方法会检查指定的bean是否已经被注册到Spring容器中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值