在spring中實例化bean無效的問題
spring中實例化bean無效
在做Struts2和Spring整合時遇到Spring實例化無效的情況,
Action中代碼如下
public class UserAction extends ActionSupport {
? ? @Resource
? ? private UserService userService;
? ? public String execute(){
? ? ? ? //userService.saveUser(new Object());
? ? ? ? System.out.println(userService);
? ? ? ? System.out.println("struts2spring整合成功");
? ? ? ? return "success";
? ? }
}applicationContext.xml中配置如下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" ? ? ? ? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ? ? ? ? xmlns:context="http://www.springframework.org/schema/context" ? ? ? ? xmlns:tx="http://www.springframework.org/schema/tx" ? ? ? ? xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ? ? ? ? ? ? ? ? http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd ? ? ? ? ? ? ? ? http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> ? ? <!-- 自動掃描與裝配bean --> ? ? <context:component-scan base-package="com.bjwl"></context:component-scan> </beans>
通過注解實例化UserService時一直得到的是null。最后經過查找,發(fā)現(xiàn)沒有導入Struts2-Spring-plugin.jar的原因。
spring實例化bean順序問題,導致注入失敗
我們可以通過Spring進行非常方便的管理bean,只需要在類上面加一個注解就可以進行bean的注入,也就是所謂的DI。今天碰到了個小問題,來總結一下。
問題如下
public abstract class TestBean {
? ? public String str;
? ??
? ? public TestBean(){
? ? ? ? this.str = initStr();
? ? }
? ??
? ? protected abstract String initStr();
}
public class TestSon extends TestBean {
? ? @Resource
? ? public String str;
? ? @Override
? ? protected String initStr() {
? ? ? ? return this.str;
? ? }
}但是發(fā)現(xiàn)這個str始終是null。
原因
在實例化TestBean的時候不能確認str已經實例化,所以是先建立對象,再進行注入str的值。那么創(chuàng)建對象的時候,根據構造方法創(chuàng)建的對象中,還沒有注入str的值,所以只能為null。
解決
我們需要確認在str已經注入進來的情況下再對父類中的str賦值,那么這個時候需要子類實現(xiàn) InitializingBean 這個接口,實現(xiàn)其中的afterPropertiesSet()
public class TestSon extends TestBean implements InitializingBean
{
? ? @Resource
? ? public String str;
? ? @Override
? ? protected String initStr() {
? ? ? ? return this.str;
? ? }
? ? @Override
? ? public void afterPropertiesSet() throws Exception {
? ? ? ? super.str = this.str;
? ? }
}問題成功解決。注入成功
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Springboot以Repository方式整合Redis的方法
這篇文章主要介紹了Springboot以Repository方式整合Redis的方法,本文通過圖文并茂實例詳解給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
MybatisPlus 插入或更新數據時自動填充更新數據解決方案
本文主要介紹了MybatisPlus 插入或更新數據時自動填充更新數據解決方案,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09

