簡體   English   中英

無法在Spring Converter中訪問自動裝配的對象

[英]Can't access autowired object in Spring converter

我正在編寫一個小型Spring應用程序,該應用程序由一個由稱為service的外觀對象和基於JSP的視圖表示的模型組成。 在這兩者之間,我有通常的Spring控制器和一個將字符串ID轉換為模型中的對象的轉換器。

此轉換器使用@Autowired service對象從service找到正確的模型對象。 問題在於,每當轉換器訪問service的方法時,都不會發生任何事情。 沒有錯誤或異常,它只會繼續並返回null。

我已經檢查了service是否已正確初始化,這似乎不是問題。 在調試時,我注意到該程序通過ThreadPoolExecutor並在我嘗試對service執行方法時在此停止。 這使我假設問題與鎖定時訪問service有關。

我已經嘗試將必要的代碼放在同步塊中,但這無濟於事。 誰能告訴我為什么我無法從Spring轉換器的@Autowired對象訪問任何方法?

以下是其價值的轉換器類:

public class IdToPublisherConverter implements Converter<String, Publisher>{

    @Autowired
    private MainService service;

    @Override
    public Publisher convert(String id) {
        return service.getPublisher(Long.getLong(id));
    }   
}

編輯:

MainService是一個Facade對象,它提供一個接口來獲取,添加,更新和刪除我的模型數據( Game對象和Publisher對象)

service.getPublisher(id)基於從JSP頁面接收到的轉換器的類型的ID從service獲取Publisher對象。 這種方法去下面的方法MainService

@Override
public Publisher getPublisher(long id) {
    Publisher publisher = repository.readPublisher(id);
    return publisher;
}

轉到:

private final Map<Long, Publisher> publishers;

...

@Override
public Publisher readPublisher(long id) {
    return publishers.get(id);
}

因此,經過一個小時的擺弄,我終於找到並解決了自己的問題。 問題與多線程無關,而與從String到long的轉換有關。 而不是使用Long.getLong(id) ,我應該使用這樣的東西:

@Override
public Publisher convert(String idString) {
    return service.getPublisher(Long.parseLong(idString));
}

嘗試將@Component批注添加到轉換器。 確保您的轉換器已在SpringConfiguration中注冊

@Configuration
@EnableWebMvc
@ComponentScan
public class ServerConfig extends WebMvcAutoConfigurationAdapter {
    @Override
    public void addFormatters(FormatterRegistry formatterRegistry) {
        converterAutoscanner(formatterRegistry);
        super.addFormatters(formatterRegistry);
    }

    @SuppressWarnings("rawtypes")
    private void converterAutoscanner(FormatterRegistry formatterRegistry)    {
        Reflections reflections = new Reflections("com.somepackege");
        Set<Class<? extends Converter>> allClasses = reflections.getSubTypesOf(Converter.class);
        allClasses.forEach(s -> {
            try {
                formatterRegistry.addConverter(s.newInstance());
            } catch (Exception e) {
                LOGGER.error(e);
            }
        });
    }
}


@Component
public class CommentConverter implements Converter<String, Comment>{
    //converter code
}

您需要將IdToPublisherConverter定義為bean。 像這樣

@Service
public class IdToPublisherConverter...

只有已初始化的bean才能使用@Autowired注釋,否則將為null。 如果IdToPublisherConverter不是bean,請使用ClasspathXmlApplicationcontext獲取spring bean。

例如,檢查您的服務是否具有@Service批注

@Service("mainService")
public class MainService...

在其中,如果您有事務方法,請不要忘記@Transactional

幾乎沒有顯示代碼,這很復雜,但是我認為這對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM