记录一下解决private方法中@Autowired无法注入问题
添加配置类
public class SpringBeanFactoryConfig implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 重写setApplicationContext方法,把ApplicationContext对象inject到当前类中作为一个静态成员变量。
*/
public void setApplicationContext(ApplicationContext appCtx) throws Exception {
applicationContext = appCtx;
}
/**
* 获取ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* @return 返回一个bean对象
*/
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
/**
* @return 返回一个bean对象
*/
public static Object getBean(Class c) {
return applicationContext.getBean(c);
}
}
加入一个bean
<bean id="springBeanFactoryConfig " class="com.xxx.xxx.SpringBeanFactoryConfig" />
private修饰方法中获取bean,并调用接口
xxxService service = (xxxService)SpringBeanFactoryConfig.getBean(xxxService.class);
原文地址:https://www.it610.com/article/1281724921046646784.htm
本文介绍了如何处理在Spring框架中,@Autowired注解无法在private方法内正常注入bean的问题。通过创建一个SpringBeanFactoryConfig配置类,实现ApplicationContextAware接口,静态持有ApplicationContext,然后在private方法内通过该配置类获取所需的bean。这种方法提供了一种在私有方法中获取bean的解决方案。
1万+

被折叠的 条评论
为什么被折叠?



