A component required a bean named 'dataSource' that could not be found - java

I am developing a simple Spring Batch jar using Spring Boot. I have used Configuration class to create dataSource bean and also annotated with #Component. But when I run the application using CommandLine Runner, it throws bean not found exception while reading the ABPBatchInfrastructure.xml.
I have did a little research of this error in google and found a solution, I have added below line in my ABPBatchInfrastructure.xml
<context:component-scan base-package="com.abp.printbatch"></context:component-scan>
Adding this line has fixed the issue but has other side effects
Spring is loading twice and all the spring core beans are getting instantiated twice.
I found this by checking the logs. Below logs for reference which shows same lines twice .
Spring JPA SQL statements are not showing up in the console even after adding spring.jpa.properties.hibernate.format_sql=true in the application-dev.properties.
is there a way to instantiate spring only once by removing the component scan in the xml and also fix the datasource bean not found issue. Please guide me. below log for your reference which clearly shows spring is loading twice.
2020-05-23 16:04:06.976 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Starting FileUploadApplication on MW7CH1-FZXX with PID 90732 (C:\gitforABP\SpringBatch\target\classes started by cac6584 in C:\gitforABP\SpringBatch)
2020-05-23 16:04:06.979 INFO 90732 --- [ main] c.a.p.FileUploadApplication : The following profiles are active: dev
2020-05-23 16:04:07.672 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-23 16:04:07.752 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 69ms. Found 1 JPA repository interfaces.
2020-05-23 16:04:08.161 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-23 16:04:08.165 WARN 90732 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2020-05-23 16:04:08.819 INFO 90732 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (Receiver class oracle.jdbc.driver.T4CConnection does not define or inherit an implementation of the resolved method abstract getNetworkTimeout()I of interface java.sql.Connection.)
2020-05-23 16:04:08.870 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-23 16:04:08.923 INFO 90732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-23 16:04:09.006 INFO 90732 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-05-23 16:04:09.152 INFO 90732 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-23 16:04:09.312 INFO 90732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-05-23 16:04:10.351 INFO 90732 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-23 16:04:10.364 INFO 90732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-23 16:04:10.771 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Started FileUploadApplication in 4.167 seconds (JVM running for 5.839)
2020-05-23 16:04:10.772 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Local
2020-05-23 16:04:11.186 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-23 16:04:11.206 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 19ms. Found 1 JPA repository interfaces.
2020-05-23 16:04:11.298 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting...
2020-05-23 16:04:11.298 WARN 90732 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2020-05-23 16:04:11.663 INFO 90732 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-2 - Driver does not support get/set network timeout for connections. (Receiver class oracle.jdbc.driver.T4CConnection does not define or inherit an implementation of the resolved method abstract getNetworkTimeout()I of interface java.sql.Connection.)
2020-05-23 16:04:11.691 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed.
2020-05-23 16:04:11.706 INFO 90732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-23 16:04:11.714 INFO 90732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-05-23 16:04:12.150 INFO 90732 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-23 16:04:12.151 INFO 90732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-23 16:04:12.170 INFO 90732 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: ORACLE
2020-05-23 16:04:12.264 INFO 90732 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2020-05-23 16:04:12.465 WARN 90732 --- [ main] o.s.b.a.batch.JpaBatchConfigurer : JPA does not support custom isolation levels, so locks may not be taken when launching Jobs
2020-05-23 16:04:12.467 INFO 90732 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: ORACLE
2020-05-23 16:04:12.467 INFO 90732 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
Entry Point
#SpringBootApplication
#ComponentScan(basePackages = "com.abp.printbatch")
public class FileUploadApplication extends PrintBatchConstants implements CommandLineRunner {
#Autowired
private NotifyYaml notify;
final static Logger logger = LoggerFactory.getLogger(FileUploadApplication.class);
public static void main(String[] args) {
SpringApplication application = new SpringApplication(FileUploadApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
#Override
public void run(String... args) throws Exception {
logger.info(notify.getEnvironment());
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" );
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
Job job=ctx.getBean(Job.class);
jobLauncher.run(job, new JobParametersBuilder()
.addString(documentClass,"InvoiceStatementDocumentation")
.addString(type, "2040-09-13")
.addString(emailID, notify.getSupportEmailId())
.addString(environment, notify.getEnvironment())
.toJobParameters());
ctx.close();
System.exit(0);
}
}
f
package com.abp.printbatch.config;
#Configuration
#Component
public class DBConfig {
#Bean
#Primary
public DataSource dataSource() {
System.out.println("");
return DataSourceBuilder.create().driverClassName("oracle.jdbc.driver.OracleDriver").url("removed")
.username("removed").password("removed").build();
}
}

As you mentioned, I have imported the xmls during app startup and removed application context initialization inside the run method. Also I removed component scan inside XML. This has fixed both datasource not found issue and Show SQL issue. Now application is working as expected. Below is my new entry point class. Thanks for all your help :)
#SpringBootApplication
#ComponentScan(basePackages = "com.abp.printbatch")
#ImportResource( { "ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" } )
public class FileUploadApplication extends PrintBatchConstants implements CommandLineRunner {
#Autowired
private NotifyYaml notify;
#Autowired
private ApplicationContext ctx;
final static Logger logger = LoggerFactory.getLogger(FileUploadApplication.class);
public static void main(String[] args) {
SpringApplication application = new SpringApplication(FileUploadApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
#Override
public void run(String... args) throws Exception {
logger.info(notify.getEnvironment());
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" );
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
Job job=ctx.getBean(Job.class);
jobLauncher.run(job, new JobParametersBuilder()
.addString(documentClass,"InvoiceStatementDocumentation") .addString(type,
"2040-09-13") .addString(emailID, notify.getSupportEmailId())
.addString(environment, notify.getEnvironment()) .toJobParameters());
ctx.close();
System.exit(0);
}
}

Related

Why did the PostConstruct execute twice in Spring

I'm using Spring to develop a web application. I just used the mechanism #PostConstruct and #Bean to invoke a function while starting up.
public class MyCache<T> {
#PostConstruct
public void init() {
System.out.println("inittttttttttt");
// something
}
}
#Configuration
#EnableScheduling
public class AppConfig {
#Bean
public MyCache<MyData> myCache() {
return new MyCache<MyData>();
}
}
public class TextFilter {
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
private MyCache<MyData> cache;
public TextFilter() {
this.context.scan("com.sensitive_words.utils");
this.context.refresh();
this.cache = this.context.getBean(MyCache.class);
}
public String filter(String originalText) {
return this.cache.get().filter(originalText);
}
}
As you see, I created a Bean and use the Bean in the class TextFilter.
However, I found that the function init() is executed twice. Here is the log:
2022-10-30 13:53:38.837 INFO 106994 --- [ main] y.c.s.SensitiveWordsApplication : Starting SensitiveWordsApplication using Java 11.0.16 on yves-Inspiron-5488 with PID 106994 (/home/yves/java_ws/sensitive_words/target/classes started by yves in /home/yves/java_ws/sensitive_words)
2022-10-30 13:53:38.839 INFO 106994 --- [ main] y.c.s.SensitiveWordsApplication : No active profile set, falling back to 1 default profile: "default"
2022-10-30 13:53:39.545 INFO 106994 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8090 (http)
2022-10-30 13:53:39.559 INFO 106994 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-10-30 13:53:39.560 INFO 106994 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68]
2022-10-30 13:53:39.654 INFO 106994 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-10-30 13:53:39.654 INFO 106994 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 763 ms
inittttttttttt
2022-10-30 13:53:39.769 INFO 106994 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
inittttttttttt
2022-10-30 13:53:40.080 INFO 106994 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8090 (http) with context path ''
2022-10-30 13:53:40.096 INFO 106994 --- [ main] y.c.s.SensitiveWordsApplication : Started SensitiveWordsApplication in 1.64 seconds (JVM running for 2.341)
Could you help me?
As I see you are setting up two different application contexts of spring
SensitiveWordsApplication does it for you
AnnotationConfigApplicationContext context you created manually in code.
This seems to be the reason, singleton bean is created one per container by default.

My h2 working, but i cant connect inside of h2-console

Yoo coder, have one issue with h2-console.When i created some entitys on start,my h2 worked and i could open my h2-console and saw there tables ,but after some time i want connect again and doesn't work now.Meanwhile i added some lines and classes,but idk why doesn't work my h2-console,cause i don't touch application properties.
After lick on conect or testconect i got this error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Mar 14 19:12:33 CET 2022
There was an unexpected error (type=Forbidden, status=403).
My github project: https://github.com/Wynnyy/bookingdoctor-project.git
logs
2022-03-14 19:12:16.222 INFO 23108 --- [ main] s.w.b.BookingdoctorApplication : Starting BookingdoctorApplication using Java 17.0.2 on DESKTOP-K3O8I67 with PID 23108 (C:\Users\Patrik Severín\IdeaProjects\bookingdoctor\target\classes started by Wynny in C:\Users\Patrik Severín\IdeaProjects\bookingdoctor)
2022-03-14 19:12:16.224 INFO 23108 --- [ main] s.w.b.BookingdoctorApplication : No active profile set, falling back to 1 default profile: "default"
2022-03-14 19:12:16.928 INFO 23108 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-03-14 19:12:16.986 INFO 23108 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 47 ms. Found 2 JPA repository interfaces.
2022-03-14 19:12:17.670 INFO 23108 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-03-14 19:12:17.682 INFO 23108 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-03-14 19:12:17.682 INFO 23108 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.58]
2022-03-14 19:12:17.780 INFO 23108 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-03-14 19:12:17.780 INFO 23108 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1503 ms
2022-03-14 19:12:17.829 INFO 23108 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-03-14 19:12:18.068 INFO 23108 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-03-14 19:12:18.080 INFO 23108 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:wynny'
2022-03-14 19:12:18.277 INFO 23108 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-03-14 19:12:18.331 INFO 23108 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.5.Final
2022-03-14 19:12:18.497 INFO 23108 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-03-14 19:12:18.627 INFO 23108 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2022-03-14 19:12:19.225 INFO 23108 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-03-14 19:12:19.232 INFO 23108 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-03-14 19:12:19.540 WARN 23108 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-03-14 19:12:19.708 INFO 23108 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will not secure any request
2022-03-14 19:12:20.112 INFO 23108 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-14 19:12:20.211 INFO 23108 --- [ main] s.w.b.BookingdoctorApplication : Started BookingdoctorApplication in 4.362 seconds (JVM running for 4.745)
2022-03-14 19:12:24.415 INFO 23108 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-03-14 19:12:24.415 INFO 23108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-03-14 19:12:24.417 INFO 23108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
By default, spring-security will protect each and every end-point - So, for /error you need to manually configure like the following -
#EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity auth) {
auth.csrf().disable()
.authorizeRequests()
.antMatchers("/error/**").permitAll() // permit-all for /error page
.anyRequest().authenticated();
}
}
For future reference:
In Spring Boot 3.0 / Spring Security 6.0 http.antMatcher() is not longer available and was replaced with http.securityMatcher().
So Subham's answer would look like that:
#Configuration
public class SecurityConfiguration {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authz) -> authz.anyRequest().permitAll())
.csrf().disable()
.securityMatcher("/error/**")
.httpBasic(withDefaults());
return http.build();
}
}

CommandLineRunner overridden run() method not executing

The problem: overridden run() method from CommandLineRunner class is not being executed.
Folder structure:
Code:
Main class:
package com.diplproj.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
CommandLineRunner class:
package com.diplproj.api.config;
import com.diplproj.api.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.sql.*;
#Component
public class DbInitialization implements CommandLineRunner {
#Autowired
CropYieldRepository cropYieldRepository;
#Autowired
CultureRepository cultureRepository;
#Autowired
LocationRepository locationRepository;
#Autowired
MicroclimateNameRepository microclimateNameRepository;
#Autowired
MicroclimateValueRepository microclimateValueRepository;
#Override
public void run(String... args) throws Exception {
System.out.println("THIS IS NOT PRINTING");
}
As it says in the println() method, this is not printing anything, only this startup logs:
2021-12-12 17:51:09.371 INFO 17832 --- [ restartedMain] com.diplproj.api.ApiApplication : Starting ApiApplication using Java 1.8.0_291 on DESKTOP-6IFP1I4 with PID 17832
2021-12-12 17:51:09.373 INFO 17832 --- [ restartedMain] com.diplproj.api.ApiApplication : No active profile set, falling back to default profiles: default
2021-12-12 17:51:09.452 INFO 17832 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-12-12 17:51:09.452 INFO 17832 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-12-12 17:51:10.706 INFO 17832 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-12-12 17:51:10.835 INFO 17832 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 111 ms. Found 5 JPA repository interfaces.
2021-12-12 17:51:11.819 INFO 17832 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-12-12 17:51:11.830 INFO 17832 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-12-12 17:51:11.831 INFO 17832 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.55]
2021-12-12 17:51:11.971 INFO 17832 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-12-12 17:51:11.971 INFO 17832 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2518 ms
2021-12-12 17:51:12.215 INFO 17832 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-12-12 17:51:12.278 INFO 17832 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.1.Final
2021-12-12 17:51:12.468 INFO 17832 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-12-12 17:51:12.676 INFO 17832 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
There are couple existing questions on this topic on Stackoverflow, but nothing helped.
Does anyone have an idea what might be causing the problem?
Thanks in advance.
This is weird to be honest. For me it works without problem.
Does your Spring project start successfully though?
Started Application in 4.728 seconds (JVM running for 5.885)
This message is missing in your log. CommandLineRunner will be executed after that message.
Another thing to note is you should declare all dependency injection variables as private but that shouldn't block Commandlinerunner anyways. Also #AutoWired is discouraged to use so try constructor dependency injection instead to see if that is causing problem.
#moze
Did you try annotating the main class as below?
#ComponentScan(basePackages = {"com.diplproj.api"})
If that works I would expect there is an issue in the package hierarchy that spring unable to scan your CommandLiner class.

HikariCP - Multiple datasources, only primary datasource's pool started (spring boot)

So, I've configured my spring boot application to handle multiple datasource everything is good, but I noticed that when I launch the application, the primary datasource's pool is started but not the others, only when they are needed (which sometimes results in nullpointer...)
2020-03-05 15:34:02.478 INFO 11172 --- [ main] be.MyApp.ESPI.EspiApplication :
Starting EspiApplication on BESVC-HQ2000928 with PID 11172 (C:\Users\...\Documents\MyApp\Others\ESPI\ESPI\target\classes started by ... in C:\Users\...\Documents\MyApp\Others\ESPI\ESPI)
2020-03-05 15:34:02.483 INFO 11172 --- [ main] be.MyApp.ESPI.EspiApplication : The following profiles are active: dev
2020-03-05 15:34:03.149 INFO 11172 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-05 15:34:03.233 INFO 11172 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 65ms. Found 2 JPA repository interfaces.
2020-03-05 15:34:03.811 INFO 11172 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-03-05 15:34:04.433 INFO 11172 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-05 15:34:04.444 INFO 11172 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-05 15:34:04.444 INFO 11172 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-03-05 15:34:04.603 INFO 11172 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-05 15:34:04.603 INFO 11172 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2047 ms
2020-03-05 15:34:04.761 WARN 11172 --- [ main] com.zaxxer.hikari.HikariConfig : FirstPool - maxLifetime is less than 30000ms, setting to default 1800000ms.
2020-03-05 15:34:04.761 INFO 11172 --- [ main] com.zaxxer.hikari.HikariDataSource : FirstPool - Starting...
2020-03-05 15:34:05.095 INFO 11172 --- [ main] com.zaxxer.hikari.pool.PoolBase : FirstPool - Driver does not support get/set network timeout for connections. (oracle.jdbc.driver.T4CConnection.getNetworkTimeout()I)
2020-03-05 15:34:05.099 INFO 11172 --- [ main] com.zaxxer.hikari.HikariDataSource : FirstPool - Start completed.
2020-03-05 15:34:05.159 INFO 11172 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-05 15:34:05.243 INFO 11172 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.4.10.Final}
2020-03-05 15:34:05.414 INFO 11172 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-05 15:34:05.554 INFO 11172 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
2020-03-05 15:34:06.519 INFO 11172 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-05 15:34:06.526 INFO 11172 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-05 15:34:06.853 WARN 11172 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-03-05 15:34:06.947 INFO 11172 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-05 15:34:07.115 INFO 11172 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-05 15:34:07.116 INFO 11172 --- [ main] be.myapp.ESPI.EspiApplication : Started EspiApplication in 5.135 seconds (JVM running for 5.744)
2020-03-05 15:34:17.044 INFO 11172 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-03-05 15:34:17.044 INFO 11172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-03-05 15:34:17.052 INFO 11172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
2020-03-05 15:34:17.087 WARN 11172 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariConfig : SecondPool- maxLifetime is less than 30000ms, setting to default 1800000ms.
2020-03-05 15:34:17.087 INFO 11172 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : SecondPool- Starting...
2020-03-05 15:34:17.176 INFO 11172 --- [nio-8080-exec-1] com.zaxxer.hikari.pool.PoolBase : SecondPool- Driver does not support get/set network timeout for connections. (oracle.jdbc.driver.T4CConnection.getNetworkTimeout()I)
2020-03-05 15:34:17.178 INFO 11172 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : SecondPool- Start completed.
As you can see FirstPool is started. Spring Application starts. Then, only when needed, the SecondPool is started... I wonder how I can force the pool to start before the application starts ?
EDIT :
My properties file are like this :
# DataSource definitions :
first.datasource.jdbc-url=jdbc:oracle:thin:#*a host*
first.datasource.username=user1
first.datasource.password=xxxxxxxxx
first.datasource.poolName=FirstPool
first.datasource.maximumPoolSize=100
first.datasource.maxLifetime=10000
second.datasource.jdbc-url=jdbc:oracle:thin:#*another host*
second.datasource.username=user2
second.datasource.password=xxxxxxxxx
second.datasource.poolName=SecondPool
second.datasource.maximumPoolSize=100
second.datasource.maxLifetime=10000
Second part :
# Profile definition
spring.profiles.active=#spring.profiles.active#
# JPA definitions
spring.jpa.show-sql=true
spring.jpa.database=oracle
# DataSource
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.dataSourceClassName=oracle.jdbc.pool.OracleDataSource
spring.datasource.hikari.dataSourceProperties.implicitCachingEnabled=true
spring.datasource.hikari.dataSourceProperties.fastConnectionFailoverEnabled=true
# Oracle specifics
oracle.net.tns_admin=${ORACLE_HOME}/NETWORK/ADMIN
The configuration class that handle the DB Configuration :
#Configuration
#PropertySource({ "classpath:application.properties", "classpath:application-${spring.profiles.active}.properties"})
#Primary
public class DBConfiguration {
#Bean(name = "FirstDataSource")
#ConfigurationProperties("first.datasource")
#Primary
public HikariDataSource FirstDataSource() {
return (HikariDataSource) DataSourceBuilder.create().build();
}
#Bean(name = "SecondDataSource")
#ConfigurationProperties("second.datasource")
public HikariDataSource SecondDataSource() {
return (HikariDataSource) DataSourceBuilder.create().build();
}
#Bean(name="FirstTM")
#Autowired
#Primary
DataSourceTransactionManager FirstTM(#Qualifier ("FirstDataSource") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
#Bean(name="SecondTM")
#Autowired
DataSourceTransactionManager SecondTM(#Qualifier("SecondDataSource") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
}
I've found the answer.
So, first, the dataSources are all created, BUT, the pool attached to it are not created until asked. So the idea is to force their initialization when starting the application.
This can be achieved like this (see How to configure hikari pool for eager initialization? ):
You can use an ApplicationLoader and get a connection at startup:
#Component
public class HikariLoader implements ApplicationRunner {
private final HikariDataSource hikariDataSource;
#Autowired
public HikariLoader(HikariDataSource hikariDataSource) {
this.hikariDataSource = hikariDataSource;
}
#Autowired
public void run(ApplicationArguments args) throws SQLException {
hikariDataSource.getConnection();
}
}
Try the following approach, It works for me with both data sources.
first.datasource.jdbc-url=jdbc-url
first.datasource.username=username
first.datasource.password=password
.
.
.
.
=================== In Java Configuration File ==================
#Primary
#Bean(name = "firstDataSource")
#ConfigurationProperties(prefix = "first.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "firstEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("firstDataSource") DataSource dataSource) {
Map<String, String> props = new HashMap<String, String>();
props.put("spring.jpa.database-platform", "org.hibernate.dialect.Oracle12cDialect");
.
.
.
return builder.dataSource(dataSource).packages("com.first.entity").persistenceUnit("firstDB")
.properties(props)
.build();
}
#Primary
#Bean(name = "firstTransactionManager")
public PlatformTransactionManager firstTransactionManager(
#Qualifier("firstEntityManagerFactory") EntityManagerFactory firstEntityManagerFactory) {
return new JpaTransactionManager(firstEntityManagerFactory);
}
second.datasource.jdbc-url=jdbc-url
second.datasource.username=username
second.datasource.password=password
.
.
.
.
=================== In Java Configuration File ==================
#Bean(name = "secondDataSource")
#ConfigurationProperties(prefix = "second.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "secondEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("secondDataSource") DataSource dataSource) {
Map<String, String> props = new HashMap<String, String>();
props.put("spring.jpa.database-platform", "org.hibernate.dialect.Oracle12cDialect");
.
.
.
return builder.dataSource(dataSource).packages("com.second.entity").persistenceUnit("secondDB")
.properties(props)
.build();
}
#Bean(name = "secondTransactionManager")
public PlatformTransactionManager secondTransactionManager(
#Qualifier("secondEntityManagerFactory") EntityManagerFactory secondEntityManagerFactory) {
return new JpaTransactionManager(secondEntityManagerFactory);
}

Cant reach Endpoint in Controller, despite it beeing intialised

I read this
and this
The main ideas are that somebody has the wrong structure and components are not beeing scanned, I have a correct one.
My controller is beeing initialised normaly. I tested it debugging and seting the breakpoint on the contructor. It is beiing runned. DEspite of the that the endpoint could not be reached by my tests nor by postman, nor in the browser. I am getting a 404.
I am using gradle. structured my code like this. Already spent 3 Hours trying to fix this, but without success.
My controller looks like this.
package com.fressnapf.microservices.orderhistory.controller.impl;
#RestController
#RequestMapping("/customer")
public class OrderHistoryController implements IOrderHistoryController {
...
#Override
#ResponseStatus(value = HttpStatus.OK)
#RequestMapping(value = "/{customerid}/orders}", method = RequestMethod.GET, produces = "application/json")
public String getOrders(#PathVariable("customerid") String customerid, #RequestParam(required = false) String timeFrom,
#RequestParam(required = false) String timeTo, #RequestParam(required = false) String openOnly) {
...
}
}
Aplplication class
package com.fressnapf.microservices.orderhistory;
#SpringBootApplication()
#ImportResource({"classpath*:applicationContext.xml"})
#Configuration()
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
this is the response I am getting
{
"timestamp": "2020-03-03T16:00:33.489+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/customer/000000000/orders"
}
this is the log I am getting in the app
2020-03-03 16:59:27.595 INFO 10406 --- [ main] c.f.m.orderhistory.Application : Starting Application on debian-sgtechedge with PID 10406 (/home/sergeygerodes/projects/scporderhistoryservice/build/classes/java/main started by sgerodes in /home/sergeygerodes/projects/scporderhistoryservice)
2020-03-03 16:59:27.602 INFO 10406 --- [ main] c.f.m.orderhistory.Application : No active profile set, falling back to default profiles: default
2020-03-03 16:59:28.414 INFO 10406 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-03 16:59:28.441 INFO 10406 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 16ms. Found 0 JPA repository interfaces.
2020-03-03 16:59:28.768 INFO 10406 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-03-03 16:59:29.035 INFO 10406 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-03 16:59:29.046 INFO 10406 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-03 16:59:29.047 INFO 10406 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29]
2020-03-03 16:59:29.140 INFO 10406 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-03 16:59:29.140 INFO 10406 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1475 ms
2020-03-03 16:59:29.294 INFO 10406 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-03 16:59:29.405 INFO 10406 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-03 16:59:29.424 INFO 10406 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:orderhistory'
2020-03-03 16:59:29.517 INFO 10406 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-03 16:59:29.565 INFO 10406 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.4.9.Final}
2020-03-03 16:59:29.660 INFO 10406 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-03 16:59:29.741 INFO 10406 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-03-03 16:59:29.886 INFO 10406 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-03 16:59:29.892 INFO 10406 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-03 17:00:28.614 WARN 10406 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=59s108ms538?s586ns).
2020-03-03 17:00:28.685 WARN 10406 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-03-03 17:00:28.845 INFO 10406 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-03 17:00:29.052 INFO 10406 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-03 17:00:29.060 INFO 10406 --- [ main] c.f.m.orderhistory.Application : Started Application in 61.937 seconds (JVM running for 62.493)
2020-03-03 17:00:33.395 INFO 10406 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-03-03 17:00:33.395 INFO 10406 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-03-03 17:00:33.404 INFO 10406 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 9 ms
the whole applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="loggerService"
class="com.fressnapf.sdk.logger.service.impl.DefaultLogService" />
<bean id="dataService"
class="com.fressnapf.sdk.dataaccess.services.impl.H2DataProvider">
<constructor-arg index="0" value="${spring.datasource.url}"/>
<constructor-arg index="1" value="${spring.datasource.username}"/>
<constructor-arg index="2" value="${spring.datasource.password}"/>
</bean>
</beans>
If you copied your controller code and pasted it here...
There is a close bracket too much. I tested it on one of my controllers and it shows the same behaviour.
#RequestMapping(value = "/{customerid}/orders-->}<--"...

Categories