Bean instantiation via factory method failed - spring-boot

I am getting below error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStorageServiceBean' defined in com.primesolutions.fileupload.settings.FileStorageProperties: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.primesolutions.fileupload.service.FileStorageService]: Factory method 'fileStorageServiceBean' threw exception; nested exception is java.lang.StackOverflowError
#ConfigurationProperties(prefix = "file")
public class FileStorageProperties {
private String uploadDir;
#Bean
public FileStorageService fileStorageServiceBean() throws Exception{
return new FileOnDiskStorageService(); // some random name; don't exist
}
public String getUploadDir() {
return uploadDir;
}
public void setUploadDir(String uploadDir) {
this.uploadDir = uploadDir;
}
}

Your method:
public FileStorageService fileStorageServiceBean() throws Exception{
return fileStorageServiceBean();
}
Is a recursive function. Which causes the stackOverflowError.

You get a java.lang.StackOverflowError because the method fileStorageServiceBean() is calling itself and that will result in an infinite loop. That code part can never end in this situation.
It could/should be something like:
#Bean
public FileStorageService fileStorageServiceBean() throws Exception{
return new FileOnDiskStorageService(); // some random name; don't exist
}
If you use a good IDE it will warn you about this. It's a good advice to always use a good IDE for Java and read the warnings. Also installing the plugins like SonarQube, Findbugs is really helpful to prevent for code issues.
Also the errors stacktrace will give a line number and some info where in the code the error occurs.

Related

The path to the driver executable must be set

Controller
#Controller
#RequestMapping
#AllArgsConstructor
public class HomeController {
private final ParseData parseArsenkin;
#GetMapping("/")
public String getHome(){
return "home";
}
#PostMapping("/")
public String postHome(){
parseArsenkin.parse();
return "result";
}
}
WebDriverConfig.java
#Configuration
public class WebDriverConfig {
#Bean
public FirefoxDriver firefoxDriver() {
WebDriverManager.firefoxdriver().setup();
return new FirefoxDriver();
}
}
ParseData.java
#Service
#AllArgsConstructor
public class ParseData {
private final FirefoxDriver firefoxDriver;
public void parse() {
String baseUrl = "http://google.com";
firefoxDriver.get(baseUrl);
System.out.println();
}
}
Error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController' defined in file [/home/michael/Documents/JavaProjects/positions/target/classes/ru/pcask/positions/controller/HomeController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parseArsenkin' defined in file [/home/michael/Documents/JavaProjects/positions/target/classes/ru/pcask/positions/service/ParseArsenkin.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'firefoxDriver' defined in class path resource [ru/pcask/positions/configuration/WebDriverConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.openqa.selenium.firefox.FirefoxDriver]: Factory method 'firefoxDriver' threw exception; nested exception is java.lang.IllegalStateException: The path to the driver executable The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
I tried to follow this tutorial: https://www.baeldung.com/java-selenium-webdriver-path-error#automated-setup
According to the tutorial I don't have to provide geckodriver manually.
What have I done wrongly?
add in WebDriverConfig System.setProperty("webdriver.gecko.driver","src/main/resources/geckodriver.exe" );

How to test complete IntegrationFlow from MessagingGateway to ServiceActivator

In our Spring Boot project we have the following IntegrationFlow configuration
package our.configs;
#Configuration
#EnableIntegration
public class MessageChannelsConfiguration {
public static final String OUTBOUND_CHANNEL = "outboundChannel";
public static final String OUTBOUND_CHANNEL_GROUP_ID = "outboundMessageGroup";
#Bean
IntegrationFlow outboundSnapshotMessageChannel(ChannelMessageStore outboundChannelMessageStore,
OutboundFixMessageService outboundMessageService) {
return f -> f
.channel(c -> c.queue(
OUTBOUND_CHANNEL,
outboundChannelMessageStore,
OUTBOUND_CHANNEL_GROUP_ID))
.handle(outboundMessageService, "processOutboundMessage");
}
#Bean
OutboundMessageService outboundFixMessageService(ObjectMapper objectMapper){
return new OutboundMessageService(objectMapper);
}
#Bean
ChannelMessageStore outboundChannelMessageStore(#Qualifier("dataSource") DataSource dataSource,
ChannelMessageStoreQueryProvider channelMessageStoreQueryProvider) {
JdbcChannelMessageStore jdbcChannelMessageStore = new JdbcChannelMessageStore(dataSource);
jdbcChannelMessageStore.setChannelMessageStoreQueryProvider(channelMessageStoreQueryProvider);
jdbcChannelMessageStore.setRegion("TX_TIMEOUT");
return jdbcChannelMessageStore;
}
#Bean
#Profile({"test"})
ChannelMessageStoreQueryProvider jdbcChannelMessageStoreQueryProvider() {
return new H2ChannelMessageStoreQueryProvider();
}
#Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller(TransactionManager transactionManager,
Initiator clientInitiator) {
return Pollers.fixedRate(500))
.maxMessagesPerPoll(1)
.advice(transactionInterceptor(transactionManager), new CheckSessionPollingAdvise(clientInitiator))
.get();
}
private TransactionInterceptor transactionInterceptor(TransactionManager transactionManager) {
return new TransactionInterceptorBuilder()
.transactionManager(transactionManager)
.propagation(Propagation.NESTED)
.build();
}
}
and the messaging Gateway which is defined as in a separate package then the above configuration
package our.businesslogic;
#MessagingGateway
public interface OutboundMessageGateway {
#Gateway(requestChannel = MessageChannelsConfiguration.OUTBOUND_CHANNEL)
void sendMarkerMessage(Object markerMessage,
#Header(ChannelMessageHeaders.RECIPIENT_ID) String institutionId,
#Header(ChannelMessageHeaders.MESSAGE_TYPE) ChannelMessageType channelMessageType);
#Gateway(requestChannel = MessageChannelsConfiguration.OUTBOUND_CHANNEL)
void sendOrderMessage(Order message,
#Header(ChannelMessageHeaders.RECIPIENT_ID) String institutionId,
#Header(ChannelMessageHeaders.MESSAGE_TYPE) ChannelMessageType channelMessageType);
}
I want to test the behavior of the complete flow including the persistence to the JdbcChannelMessageStore (and later also the transactional scenarios) with JUnit5.
E.g.
#Test
void whenSendTrancheMessage_givenPollingBlockedByAdvise_thenCorrectNumberOfMessagesOnQueue() {
//given
String recipientId = "Mocked-recipient";
List<Order> orders = Arrays.asList(
new Order(),
new Order(),
new Order(),
new Order()
);
//when
clientInitiator.stopConnection(); // Queue will not be read as long as
// there is no connection
orders.forEach(order->
outboundMessageGateway.sendOrderMessage(order,recipientId,ChannelMessageType.SNAPSHOT));
//then
Assertions.assertThat(outboundChannelMessageStore.messageGroupSize(FixMessageChannelsConfiguration.OUTBOUND_CHANNEL_GROUP_ID))
.isEqualTo(orders.size());
}
#Test
void whenSendTrancheMessage_givenPollingIsNotBlocked_thenMessagesAreReceivedByHandler() {
//some test code with mocked ServiceActivator
}
I have tried with two different ways
as an Integration test with #SpringBootTest
as a context specific JUnit test with #ContextConfiguration and #SpringIntegrationTest
In case of 1) my tests are working when called separately, but are failing with the following exception when they are run together with existing integration tests
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class p
ath resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation vi
a factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servl
et.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.h2.jdbc.JdbcSQLNonTransientConnection
Exception: Exception opening port "9092" (port may be in use), cause: "java.net.BindException: Address already in use: JVM_Bind" [900
61-199]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:483)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowir
eCapableBeanFactory.java:1336)
In case of 2) the following exception is thrown showing problems with the outboundMessageGateway
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
... ... ...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'outboundMessageGateway': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [our.businesslogic.OutboundMessageGateway]: Specified class is an interface
I would appreciate it very much if someone could help me to solve this issues.
Exception opening port "9092"
You probably need to add a #DirtiesContext along side with the mentioned #SpringBootTest.
Failed to instantiate [our.businesslogic.OutboundMessageGateway]
If you don't use Spring Boot in your test environment, you must be explicit #EnableIntegration and #IntegrationComponentScan must be there to Spring Integration infrastructure available.
See docs for more info: https://docs.spring.io/spring-integration/docs/current/reference/html/overview.html#configuration-enable-integration
Assertions.assertThat(outboundChannelMessageStore.messageGroupSize(FixMessageChannelsConfiguration.OUTBOUND_CHANNEL_GROUP_ID))
.isEqualTo(orders.size());
You can't check this if your handle(outboundMessageService, "processOutboundMessage") is not stopped. Since you have a poller for the queue channel, it is going to pull all the message from the store and lets that handler to process them. So, there is going to be nothing in the store at the moment you try to verify it (or some wrong unexpected number).

Encountered invalid #Scheduled method 'methodName': Only no-arg methods may be annotated with #Scheduled

plz I don't know wath is the exact problem in the code if I add Scheduled annotatiçon in my code suddenly this error appears
if you have any soulustion please.
plz I don't know wath is the exact problem in the code if I add Scheduled annotatiçon in my code suddenly this error appears
if you have any soulustion please.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
12-09-2019 18:11:54.908 [restartedMain] ERROR o.s.boot.SpringApplication.reportFailure - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'missionResource': Unsatisfied dependency expressed through field 'missionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'missionImpl' defined in file [C:\Users\El Oussa\Desktop\vgas-api\vgas-manager\target\classes\ma\valueit\vgas\manager\business\impl\MissionImpl.class]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid #Scheduled method 'editMission': Only no-arg methods may be annotated with #Scheduled
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
I have added #EnableScheduling in SpringBootApplication
--------------------------------------------------------
#SpringBootApplication
#EnableScheduling
#ComponentScan("com.qaiboub.vs")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#Service
public class MissionImpl extends CrudManagerImpl<MissionDto, Integer, MissionEntity, MissionService, MissionConverter> implements MissionManager {
#Autowired
private MissionService missionService;
#Autowired
private MissionConverter missionConverter;
enter code here
#Override
public MissionService getService() {
return missionService;
}
#Override
public MissionConverter getConverter() {
return missionConverter;
}
#Scheduled(cron = "0 15 18 * * *")
public void editMission(Integer id, MissionDto missionDto) {
if (StringUtils.isEmpty(id)) {
throw new MissingIdException();
}
if (missionDto == null) {
throw new InvalidPayloadException();
}
if (!id.equals(missionDto.getId())) {
throw new BusinessException(CommonErrorCode.TRYING_TO_EDIT_ANOTHER_ENTITY);
}
missionEntity = missionConverter.convertFrom(missionDto);
missionEntity = missionService.save(missionEntity);
}
}
remove the function arg. Scheduler don't take arg in their functions
You need to remove all the arguments from the function, the scheduler does not accept any argument
public void syncData(#RequestParam(name = "created_at_from") String createdAtFrom,
#RequestParam(name = "created_at_to") String createdAtTo) {}
Correct format is
public void syncData() throws Exception {}
Use this link for additional details:
https://www.baeldung.com/shedlock-spring

Cucumber Spring and class configuration

I'm struggling with Cucumber and Spring configuration.
I'm writing selenium framework using Page Object Pattern, with BrowserFactory.
When I use #ComponentScan, #Component and #Autowire annotations everything works fine, but when I want to create a bit more complicated bean with #Bean annotation (BrowserFactory which registers few browser drivers) in #Configuration class it does not work, during debug I'm getting nulls on every single variable I'm trying to Autowire.
I'm using Spring 4.2.4, all cucumber dependencies in version 1.2.4.
Config:
#Configuration
public class AppConfig {
#Bean
#Scope("cucumber-glue")
public BrowserFactory browserFactory() {
BrowserFactory browserFactory = new BrowserFactory();
browserFactory.registerBrowser(new ChromeBrowser());
browserFactory.registerBrowser(new FirefoxBrowser());
return browserFactory;
}
#Bean(name = "loginPage")
#Scope("cucumber-glue")
public LoginPage loginPage() throws Exception {
return new LoginPage();
}
#Bean(name = "login")
#Scope("cucumber-glue")
public Login login() {
return new Login();
}
}
POP:
public class LoginPage extends Page {
public LoginPage() throws Exception {
super();
}
...
}
Page:
public class Page {
#Autowired
private BrowserFactory browserFactory;
public Page() throws Exception{
...
}
}
Login:
public class Login {
#Autowired
private LoginPage loginPage;
public Login(){}
...
}
Steps:
#ContextConfiguration(classes = {AppConfig.class})
public class LoginSteps {
#Autowired
Login login;
public LoginSteps(){
}
#Given("^an? (admin|user) logs in$")
public void adminLogsIn(Login.User user) throws Exception {
World.currentScenario().write("Logging in as " + user + "\n");
login.as(user);
}
}
Error:
cucumber.runtime.CucumberException: Error creating bean with name 'LoginSteps': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: Login LoginSteps.login; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'login': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private LoginPage Login.loginPage; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginPage' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [LoginPage]: Factory method 'loginPage' threw exception; nested exception is java.lang.NullPointerException
And now for the fun part...
BrowserFactory in World class is properly Autowired!!
World:
public class World {
#Autowired
private BrowserFactory browserFactory;
...
}
So I'll answer my own question:)
Issue was that I was calling BrowserFactory inside of Page constructor.
Looks like this bean was not yet created and was causing NPEs.
In order to fix that I:
Added #Lazy annotation to configuration (all elements that use this configuration, both defined in that class and those which will be found by Scan will be created as Lazy)
Moved call to Browser Factory to #PostConstruct method
Two more things to increase readability of Spring config:
Added #ComponentScan to configuration
Classes with no constructor parameters are annotated with #Component and #Scope("cucumber-glue") annotation so bean creation can be removed from AppConfig.class

How to get JobExecutionContext from a Partitioner

I have a InitTasklet that runs before an Master/Slave with partitioner strategy. In this initial tasklet I access the database and get a list with ids and put into context:
chunkContext.getStepContext().getStepExecution().getJobExecution()
.getExecutionContext().put("listaBancos", lista);
I need to access this list in my Partitioner
I tried this way with no success: the method beforeJob is never executed.
public class BancoPartitioner extends JobExecutionListenerSupport ...
#Override
public void beforeJob(JobExecution jobExecution) {
this.context = jobExecution.getExecutionContext();
super.beforeJob(jobExecution);
}
I tried to autowired the stepExecution this way:
#Value("#{stepExecution}")
private StepExecution stepExecution;
but I get an exception:
Error creating bean with name 'bancoPartitioner': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.StepExecution .....stepExecution; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'stepExecution' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'.
Is there any way to access the Execution context from a Partitioner?
It works with scope="step" in the declaration of Partitioner Bean, as bellabax explained.

Resources