一,新建一个util类,TestUtil:
public class TestUtil {
private MyService myService;
public MyService getMyService() {
return myService;
}
public void setMyService(MyService myService) {
this.myService = myService;
}
public void test(){
System.out.println("myService = " + myService);
}
}
二,spring xml配置如下:
<bean name="testUtil" class="com.rgm.util.testUtil">
<property name="myService" ref="myService" />
</bean>
三,action使用:
TestUtil testUtil = new TestUtil();
testUtil.test();
四,输出结果:myService = null
五,原因分析:
由于testUtil是在new出来的,testUtil不受spring管理,因此myService并没有注入到testUtil实例中。
六,解决办法:
1)在action增加TestUtil属性,并设置get/set方法,在xml里面注入action的testUtil属性
2)新建spring工具类获得相应的bean
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
<bean id="springContextUtil" class="com.rgm.util.SpringContextUtil" scope="singleton"/>
public class TestUtil {
private MyService myService = (MyService)SpringContextUtil.getApplicationContext().getBean("myService");
public void test(){
System.out.println(myService.toString());
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。