BeanCreationException с бинами типа @Service

Добрый день.

Есть middleware-сервис(@Service) для доступа к компонентам (@Component) core-модуля.
При запуске приложения возникла ошибка:

2018-08-03 16:38:05.378 WARN  [localhost-startStop-1] com.haulmont.cuba.core.sys.CubaDefaultListableBeanFactory - Bean creation exception on non-lazy FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'atl_ReadingService': Invocation of init method failed; nested exception is java.lang.ExceptionInInitializerError
2018-08-03 16:38:05.421 WARN  [localhost-startStop-1] com.haulmont.cuba.core.sys.CubaDefaultListableBeanFactory - Bean creation exception on non-lazy FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'atl_ReadingService': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.sun.proxy.$Proxy65
...
2018-08-03 16:38:08.807 WARN  [localhost-startStop-1] com.haulmont.cuba.core.sys.CubaClassPathXmlApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'atl_ReadingService': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.sun.proxy.$Proxy65
2018-08-03 16:38:08.807 INFO  [localhost-startStop-1] com.haulmont.cuba.core.sys.CubaThreadPoolTaskScheduler - Shutting down ExecutorService 'scheduler'
2018-08-03 16:38:08.831 ERROR [localhost-startStop-1] com.haulmont.cuba.core.sys.AbstractWebAppContextLoader - Error initializing application
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'atl_ReadingService': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.sun.proxy.$Proxy65
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at com.haulmont.cuba.core.sys.CubaClassPathXmlApplicationContext.<init>(CubaClassPathXmlApplicationContext.java:27) ~[cuba-global-6.8.9.jar:6.8.9]
	at com.haulmont.cuba.core.sys.AbstractAppContextLoader.createApplicationContext(AbstractAppContextLoader.java:90) ~[cuba-global-6.8.9.jar:6.8.9]
	at com.haulmont.cuba.core.sys.AbstractAppContextLoader.initAppContext(AbstractAppContextLoader.java:62) ~[cuba-global-6.8.9.jar:6.8.9]
	at com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.contextInitialized(AbstractWebAppContextLoader.java:75) ~[cuba-global-6.8.9.jar:6.8.9]
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4745) [catalina.jar:8.5.23]
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5207) [catalina.jar:8.5.23]
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.5.23]
	at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752) [catalina.jar:8.5.23]
	at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728) [catalina.jar:8.5.23]
	at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734) [catalina.jar:8.5.23]
	at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1144) [catalina.jar:8.5.23]
	at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1878) [catalina.jar:8.5.23]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_161]
	at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_161]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_161]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_161]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_161]
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.sun.proxy.$Proxy65
	at sun.reflect.GeneratedConstructorAccessor13.newInstance(Unknown Source) ~[na:na]
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_161]
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_161]
	at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:739) ~[na:1.8.0_161]
	at com.haulmont.cuba.web.sys.remoting.LocalServiceProxy.afterPropertiesSet(LocalServiceProxy.java:55) ~[cuba-web-6.8.9.jar:6.8.9]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
	... 28 common frames omitted

Методом проб и ошибок выяснил, что ошибку вызывают методы сервиса, принимающие в параметрах ENUM’ы и интерфейсы, объявленные модуле global.


/* СЕРВИС */
import org.springframework.stereotype.Service;
import ru.sec2.atlas.entityservices.readings.ElectricityReadingHelper;
import ru.sec2.atlas.entityservices.readings.ReadingHelper;
import ru.sec2.atlas.meter.readings.Reading;
import ru.sec2.atlas.meter.readings.electrisity.*;
/*...*/
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;

@Service(ReadingService.NAME)
public class ReadingServiceBean implements ReadingService {
    @Inject
    private ReadingHelper readingHelper;
    @Inject
    private ElectricityReadingHelper electricityReadingHelper;
    /*...*/
    /**
     * ВЫЗЫВАЕТ ОШИБКУ
     */
    @Override
    public List<Reading> getReadings(ElectricityReadingGroup group, IElectricityReadingType type,
                                     String mac, int tariff, Date dateStart, Date dateEnd) {
        return electricityReadingHelper.getReadings(group, type, mac, tariff, dateStart, dateEnd); // return null; // не влияет
    }

   /**
     * НЕ ВЫЗЫВАЕТ ОШИБОК
     */
    @Override
    public List<Reading> getReadings(int media, int group, int type, String mac, int tariff, Date dateStart, Date dateEnd) throws RuntimeException {
        return readingHelper.getReadings(media, group, type, mac, tariff, dateStart, dateEnd);
    }
}

/* Интерфейс */
import com.haulmont.cuba.core.global.DataManager;
import org.springframework.stereotype.Service;
import ru.sec2.atlas.entityservices.readings.ElectricityReadingHelper;
import ru.sec2.atlas.entityservices.readings.ReadingHelper;
import ru.sec2.atlas.meter.readings.Reading;
import ru.sec2.atlas.meter.readings.electrisity.*;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;

public interface ReadingService {
    String NAME = "atl_ReadingService";
	/*...*/

Не подскажете, в чем проблема?

Воспроизвел проблему:
Один из ENUM’ов, принимающихся в параметрах использует Metadata.getClass(String) (и, соответственно, имеет поле типа MetaClass). Именно такое перечисление вызывает ошибку при старте приложения, если принимается в параметрах методов @Service-бина. На @Component такого влияния не оказывается.
CoreGlobalEnumTest.zip (84,4 КБ)

1 симпатия

В Java так делать нельзя:

public enum MetadataEnum implements EnumClass<Integer> {

    NEW_ENTITY(10, "cge$NewEntity");

    private Integer id;
    private MetaClass metaClass;

    MetadataEnum(Integer value, String meta) {
        this.id = value;
        this.metaClass = AppBeans.get(Metadata.class).getClass(meta); /* ПОЛОМКА */
    }

MetaClass не является неизменяемым типом. У приложений среднего слоя и клиентов - свои экземпляры MetaClass. В Java перечисления должны хранить и предоставлять только неизменяемые данные. Иначе велик риск, что вы столкнётесь с утечками памяти и race condition в потоках.

Более того, нет никакой гарантии, что класс перечисления не загрузится раньше, чем стартовал контекст приложения. В этом случае AppBeans вернёт null и всё приложение упадёт.

Если вам требуется ссылка на MetaClass - получайте её в методе, а перечисление должно хранить простую строку.

2 симпатии

Спасибо, в боевом приложении как раз перевел на хранение строки с сохранением логики работы методов .getMetaClass().
Так понимаю, именно race condition и вызывало ошибку в конечном счете?

По сути, класс перечисления был загружен раньше, чем стартовал контекст. Это даже не гонка, это просто порядок инициализации.

2 симпатии