java类不能获取spring定义的Bean对象
初学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对象
}
}
------解决方案--------------------楼主你main方法里面就
一句Object obj = SpringBeanUtil.getBean("userService");什么时候启动spring了