Spring boot Не удалось загрузить контекст приложения

Имейте приложение springboot, которое читает файлы из исходного каталога с помощью файлового входящего адаптера. Для него написаны тестовые примеры junit. Тестовый пример Junit успешно выполняется в моем локальном затмении. но столкнулся с проблемой при запуске из bamboo/jenkins, развернутого на другом компьютере.

Не удалось загрузить контекст приложения во время выполнения тестовых примеров весенней загрузки junit. 'filesInChannel.adapter.source' Причина: java.lang.IllegalArgumentException: Исходный каталог [/filepath] не существует.

Какова причина маршрута для этого. Любое предложение/совет по этому поводу? это из-за какой-то проблемы с разрешениями на машине, развернутой на бамбуке?

Написали отдельную конфигурацию для тестового случая. Но не уверен, почему он указывает на исходный xml для загрузки контекста приложения при выполнении тестовых случаев.

Ошибка:

   java.lang.IllegalStateException: Failed to load ApplicationContext
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filesInChannel.adapter': Cannot resolve reference to bean 'filesInChannel.adapter.source' while setting bean property 'source'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filesInChannel.adapter.source': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Source directory [/filepath] does not exist.
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filesInChannel.adapter.source': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Source directory [/filepath] does not exist.
    Caused by: java.lang.IllegalArgumentException: Source directory [/filepath] does not exist.

исходный код файла-process.xml:

<file:inbound-channel-adapter id="filesInChannel"
        directory="/filepath/" auto-startup="false" scanner="recursiveScanner" auto-create-directory="true">
                <integration:poller id="poller" max-messages-per-poll="${max.messages.per.poll}" fixed-rate="${message.read.frequency}" task-executor="pollingExecutor">
            <integration:transactional transaction-manager="transactionManager" />
        </integration:poller>       
    </file:inbound-channel-adapter>

прецедент:

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = TestConfig.class)
public class FileApplicationTests {

    @Test
    public void contextLoads() {
    }

}

Конфиг Теста:

@Configuration
@ImportResource({ "classpath:test-file-process.xml" })
public class TestConfig {

}

исходный код test-file-process.xml:

<file:inbound-channel-adapter id="filesInChannel"
        directory="file:${java.io.tmpdir}/filepath/" auto-startup="false" scanner="recursiveScanner" auto-create-directory="true">
                <integration:poller id="poller" max-messages-per-poll="${max.messages.per.poll}" fixed-rate="${message.read.frequency}" task-executor="pollingExecutor">
            <integration:transactional transaction-manager="transactionManager" />
        </integration:poller>
    </file:inbound-channel-adapter>

Журнал :

018-09-11 14:54:39.893  INFO 9224 --- [           main] c.o.i.f.h.ErrorHandlerTest               : Starting ErrorHandlerTest on pc226116 with PID 9224 (started by test in D:\Repo\file-handler)
2018-09-11 14:54:39.896  INFO 9224 --- [           main] c.o.i.f.h.ErrorHandlerTest               : No active profile set, falling back to default profiles: default
2018-09-11 14:54:39.901  INFO 9224 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@22dc59b2: startup date [Tue Sep 11 14:54:39 IST 2018]; root of context hierarchy
2018-09-11 14:54:39.910  INFO 9224 --- [           main] o.s.b.f.x.XmlBeanDefinitionReader        : Loading XML bean definitions from class path resource [test-file-process.xml]
2018-09-11 14:54:40.158  INFO 9224 --- [           main] o.s.i.c.IntegrationRegistrar             : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2018-09-11 14:54:40.161  INFO 9224 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'configurationValidator' with a different definition: replacing [Generic bean: class [com.interfaces.file.handler.ConfigurationValidator]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\Repo\file-handler\target\classes\com\interfaces\file\handler\ConfigurationValidator.class]] with [Generic bean: class [com.interfaces.file.handler.ConfigurationValidator]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=init; destroyMethodName=null; defined in class path resource [test-file-process.xml]]
2018-09-11 14:54:40.164  INFO 9224 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'cacheManager' with a different definition: replacing [Generic bean: class [com.interfaces.file.handler.CacheManager]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\Repo\file-handler\target\classes\com\interfaces\file\handler\CacheManager.class]] with [Generic bean: class [org.springframework.cache.support.SimpleCacheManager]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [test-file-process.xml]]
2018-09-11 14:54:40.167  INFO 9224 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'headerEnricher' with a different definition: replacing [Generic bean: class [com.interfaces.file.handler.HeaderEnricher]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\Repo\file-handler\target\classes\com\interfaces\file\handler\HeaderEnricher.class]] with [Generic bean: class [com.interfaces.file.handler.HeaderEnricher]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [test-file-process.xml]]
2018-09-11 14:54:40.182  INFO 9224 --- [           main] .f.x.DefaultBeanDefinitionDocumentReader : Skipped XML bean definition file due to specified profiles [aws] not matching: class path resource [test-file-process.xml]
2018-09-11 14:54:40.548  INFO 9224 --- [           main] o.s.b.f.x.XmlBeanDefinitionReader        : Loading XML bean definitions from class path resource [file-process.xml]
2018-09-11 14:54:40.795  INFO 9224 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'transactionManager' with a different definition: replacing [Generic bean: class [org.springframework.integration.transaction.PseudoTransactionManager]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [test-file-process.xml]] with [Generic bean: class [org.springframework.integration.transaction.PseudoTransactionManager]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [file-process.xml]]

comment
Можете ли вы поделиться выводом журнала при запуске теста? Я предполагаю, что адаптер входящего канала вашего теста сначала определяется, а затем переопределяется адаптером, определенным в file-process.xml.   -  person Andy Wilkinson    schedule 11.09.2018
comment
да исправить. Можете ли вы предоставить решение для этого. Прикрепил журнал, где его переопределение   -  person Jessie    schedule 11.09.2018
comment
Смотрите мой ответ ниже.   -  person Artem Bilan    schedule 11.09.2018


Ответы (1)


Я думаю, что проблема здесь в том, что <file:inbound-channel-adapter> создает на самом деле несколько bean-компонентов, где один из них FileReadingMessageSource с условием вроде:

Assert.isTrue(this.directory.exists(),
            "Source directory [" + this.directory + "] does not exist.");

просто в своем afterPropertiesSet() независимо от auto-startup="false".

Боюсь, именно этот бин не переопределяется, просто потому, что его id генерируется автоматически.

Вот так другой конфиг не помогает.

Я предлагаю вам взглянуть на поддержку профилей: https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-definition-profiles

И заверните этот <file:inbound-channel-adapter> во что-то вроде:

<beans:beans profile="!test">
</beans:beans>
person Artem Bilan    schedule 11.09.2018
comment
Попробовал это решение, обернув код внутри beans: bean profile. Но после добавления определения bean также получил исключение ниже. xmlns:beans= springframework.org/schema/beans. Исключение: SaxParseException: не удается найти объявление элемента «beans» - person Jessie; 11.09.2018
comment
Ой! Это должно быть <beans:beans>. Хорошо, если вы используете префикс beans для xmlns="http://www.springframework.org/schema/beans". Иначе это просто <beans profile="!test"> - person Artem Bilan; 11.09.2018
comment
Извините Артем...опечатка...пробовал только ‹beans:beans›.. но вылетает исключение. Нужно ли нам добавлять какую-либо версию в schemalocation. xmlns=springframework.org/schema/beans/spring-beans-4.3. xsd? - person Jessie; 11.09.2018
comment
Ну, это исходит из корня конфигурации Spring XML. У вас определенно должен быть такой schemaLocation в вашей конфигурации. Вам просто нужно повторить корневой тег вашего конфига, с префиксом или полностью без него, если вы его там не используете. - person Artem Bilan; 11.09.2018
comment
Я поднял исправление, чтобы упростить жизнь: github.com/spring-projects /spring-integration/pull/2562 - person Artem Bilan; 11.09.2018