java类不能获取spring定义的Bean对象

xujun832 xujun832 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
初学ssh,我现在想在普通的java类中获取spring中配置的bean对象,我按网上说的定义了一个SpringBeanUtil类并实现org.springframework.context.ApplicationContextAware这个接口,如下

public Class SpringBeanUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException{
SpringBeanUtil.applicationContext = arg0;
}

public static Object getBean(String name){
return applicationContext .getBean(name);
}
}

同时在applicationContext.xml中配置了该类的bean信息
<bean id="springBeanUtil " class="com.test.SpringBeanUtil "></bean>

此时我写了个测试类TestDemo来获取bean对象,但获取不到,SpringBeanUtil类中的applicationContext为null,也就是说spring容器在启动的时候没有给SpringBeanUtil类的applicationContext属性赋值,不知是什么原因,谢谢!
TestDemo
public class TestDemo{
public static void main(String[] args){
Object obj = SpringBeanUtil.getBean("userService");//其中userService是在applicationContext.xml配置的一个bean对象
}
}
...全文

相关推荐

评论 10
收藏 已收藏
分享
返回顶部
xujun832
Web 开发 81,108 成员 341,721 内容