获取所有bean的名字

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;



WebApplicationContext ac = ContextLoaderListener.getCurrentWebApplicationContext(); //ApplicationContext ac = SpringContext.getApplicationContext(); String[] strings=ac.getBeanDefinitionNames(); System.out.println(strings.length); AutowireCapableBeanFactory beanFactory = ac.getAutowireCapableBeanFactory(); beanFactory.autowireBean(a); String name = a.getClass().getName(); beanFactory.initializeBean(a, name); strings=ac.getBeanDefinitionNames(); System.out.println(strings.length); for (String string : strings) { System.out.println(string); }

 

转载于:https://www.cnblogs.com/tonggc1668/p/7498677.html

在Spring框架中,根据service名字获取bean是一个常见的操作。Spring提供了多种方法来获取bean实例。以下是几种常用的方法: 1. **使用`ApplicationContext`获取bean**: ```java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class BeanExample { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MyService myService = (MyService) context.getBean("myService"); myService.performAction(); } } ``` 2. **使用`@Autowired`注解**: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyComponent { @Autowired private MyService myService; public void execute() { myService.performAction(); } } ``` 3. **使用`BeanFactory`获取bean**: ```java import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class BeanFactoryExample { public static void main(String[] args) { BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml")); MyService myService = (MyService) factory.getBean("myService"); myService.performAction(); } } ``` 这些方法都可以根据service的名字获取到对应的bean实例。选择哪种方法取决于具体的应用场景和Spring的配置方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值