@Autowired не работает для класса, который реализуется из библиотеки jpos, отличной от Spring.

Я использую сервер jpos Q2 с диспетчером транзакций из моего весеннего загрузочного приложения, однако, когда я пытаюсь реализовать DI в своем классе, который реализуется из интерфейса Jpos TransactionParticipant, он дает мне исключение нулевого указателя.

Насколько я понимаю, я перепробовал все варианты, которые могут быть в весенней загрузке для IoC. Кажется, что сторонняя библиотека TransactionParticipant не может зарегистрировать ее в модуле Spring IoC/DI.

package com.fonepay.iso;

@Service("processIsoTxn")
public class ProcessIsoTxn implements TransactionParticipant{
@Autowired
    private CbsTxnService cbsTxnService;

    @Override
    public int prepare(long id, Serializable context) {
        Context ctx = (Context) context;
        try{

            ISOMsg request = (ISOMsg) ctx.get("REQUEST");

            //Call local processing Message
            //CbsTxnService cbsTxnService = new CbsTxnServiceImpl();
            ISOMsg response = cbsTxnService.createFinancialTxn(request);

            ctx.put("RESPONSE", response);
            return PREPARED;

        }catch(Exception ex){
            System.out.println("Process Iso Txn | error | "+ex);
        }

        return 0;
    }
}
package com.fonepay.service.impl;

@Service("cbsTxnService")
@Transactional
public class CbsTxnServiceImpl implements CbsTxnService{
     public ISOMsg createFinancialTxn(ISOMsg isoMsg) {...}
}
@SpringBootApplication
@ComponentScan("com.fonepay")
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class JposserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(JposserverApplication.class, args);
    }
}

Я постоянно получаю java.lang.NullPointerException в строке ISOMsg response = cbsTxnService.createFinancialTxn(request);


person Diwas Sapkota    schedule 01.09.2019    source источник


Ответы (2)


  • Попробуйте этот, замените аннотацию @Autowired
  • Попробуйте использовать конструктор
@Service("processIsoTxn")
public class ProcessIsoTxn implements TransactionParticipant{

 private CbsTxnService cbsTxnService;

  public ProcessIsoTxn (CbsTxnService cbsTxnService) {
    this.cbsTxnService = cbsTxnService;
  }

person Dulaj Kulathunga    schedule 01.09.2019
comment
Причина: java.lang.NoSuchMethodException: Нет такого конструктора ... еще 31 ‹/nested-exception› org.jpos.core.ConfigurationException: com.fonepay.iso.ProcessIsoTxn (javax.management.ReflectionException) на org.jpos. q2.QFactory.newInstance(QFactory.java:323) в org.jpos.transaction.TransactionManager.createParticipant(TransactionManager.java:766) в org.jpos.transaction.TransactionManager.initGroup(TransactionManager.java:757) в org.jpos .transaction.TransactionManager.initParticipants(TransactionManager.java:739) - person Diwas Sapkota; 02.09.2019

Если кому-то интересно, вот как я нашел обходной путь, см.: https://confluence.jaytaala.com/display/TKB/Super+simple+approach+to+accessing+Spring+beans+from+не-Spring+управляемые+классы+и+POJO

private CbsTxnService getCbsTxnService() {
        return SpringContext.getBean(CbsTxnService.class);
    }

ISOMsg response = getCbsTxnService().createFinancialTxn(request);

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext context;

    /**
     * Returns the Spring managed bean instance of the given class type if it exists.
     * Returns null otherwise.
     * @param beanClass
     * @return
     */
    public static <T extends Object> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {

        // store ApplicationContext reference to access required beans later on
        SpringContext.context = context;
    }
}
person Diwas Sapkota    schedule 02.09.2019