在非Bean中如何引入Bean
在非Bean中引入Bean,可以通过Spring的ApplicationContext来获取Bean实例。
- 首先需要在Spring配置文件中定义Bean
<bean id="myBean" class="com.example.MyBean" />
- 在非Bean实例中使用ApplicationContext获取Bean实例
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyNonBeanClass {
public void doSomething() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
MyBean myBean = (MyBean) context.getBean("myBean");
myBean.doSomething();
}
}
通过ApplicationContext的getBean方法获取指定id的Bean实例,然后就可以使用Bean的方法或属性了
原文地址: https://www.cveoy.top/t/topic/eOud 著作权归作者所有。请勿转载和采集!