亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

運行從 springboot 項目打包的 jar 時無法獲取 bean

運行從 springboot 項目打包的 jar 時無法獲取 bean

料青山看我應如是 2023-03-17 17:09:02
我可以在 IDEA 中很好地運行我的 springboot 項目,但是當將它打包到一個 jar 并使用 java 命令運行時,從 spring 上下文獲取 bean 時只得到 java.lang.NullPointerException。剛剛出現錯誤的第一堂課:@Servicepublic class MdspiImpl extends CThostFtdcMdSpi {public MdspiImpl(CThostFtdcMdApi mdapi) {        m_mdapi = mdapi;        logger.info("MdspiImpl is creating...");        ***mdr = SpringContextUtil.getBean("marketDataRobot");//this is the error code***    }}第二類:@Servicepublic class MarketDataRobot {}SpringContextUtil 類:@Component("SpringContextUtil")public class SpringContextUtil implements ApplicationContextAware {    private static ApplicationContext applicationContext;    public static <T> T getBean(String name) {        return (T) applicationContext.getBean(name);    }}漸變文件:jar {    baseName = 'programmingTrading'    version =  '0.1.0'    manifest {        attributes 'Main-Class': 'com.blackHole.programmingTrading'    }}這是使用 SpringContextUtil 獲取 bean 的部分原因......非常感謝!
查看完整描述

2 回答

?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

SpringContextUtil不應該像您正在做的那樣靜態訪問...因為您將其定義為@Component執行以下操作;


@Service

public class MdspiImpl extends CThostFtdcMdSpi {


    @Autowired

    private SpringContextUtil springContextUtil;


    public MdspiImpl(CThostFtdcMdApi mdapi) {

        m_mdapi = mdapi;

        logger.info("MdspiImpl is creating...");

        ***mdr = springContextUtil.getBean("marketDataRobot");

    }

}

由于SpringContextUtil不是通過 Spring 注入,而是簡單地靜態訪問,因此applicationContext它的內部被忽略并且在您的情況下為 null。


同時去掉static修飾符;


@Component

public class SpringContextUtil implements ApplicationContextAware {


    private ApplicationContext applicationContext;


    // include getter/setter for applicationContext as well


    public <T> T getBean(String name) {

        return (T) applicationContext.getBean(name);

    }

}

編輯


來自最新示例項目的麻煩;


@Service

public class ExampleService {

    @Autowired

    private Logger logger;


    public ExampleService() {

        this.logger=logger;

        logger.info("Im working");

    }

}

這里Logger將是 null,當ExampleService構造函數被觸發時,因為構造函數在注入開始之前被調用,但是如果您通過所述構造函數合并注入,則可以合并此行為,如下所示;


@Service

public class ExampleService {


    private final Logger logger;


    public ExampleService(Logger logger) {

        this.logger = logger;

        logger.info("Im working");

    }

}

完美運行,沒有任何問題......


查看完整回答
反對 回復 2023-03-17
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

您永遠不應該像使用 this 那樣以編程方式訪問 bean SpringContextUtil,只需注入MarketDataRobot的構造函數MdspiImpl就可以了(因為它被注釋為@Service)。首選的方法是使用構造函數注入而不是字段注入,這將使您更容易編寫單元測試。@Autowired如果你只有一個構造函數,你也可以去掉。



查看完整回答
反對 回復 2023-03-17
  • 2 回答
  • 0 關注
  • 407 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號