#RestController not working with spring-data-jpa starters - spring

I am trying to create a simple Spring Boot project which uses spring data jpa for DB interactions.
Application Class:
package org.railway.fms.documentmgmt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories(basePackages = {"org.railway.fms.documentmgmt.repository"})
#EntityScan(basePackages= {"org.railway.fms.documentmgmt.entities"})
public class FMSApplication {
public static void main(String[] args) {
SpringApplication.run(FMSApplication.class, args);
}
}
Controller Class:
package org.railway.fms.documentmgmt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class NatureOfDocumentRestService {
#GetMapping("/document/nature")
public String getNatureOfDocuments() {
return "test";
}
}
build.gradle file :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.4.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'document-mgmt'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile ("org.springframework.boot:spring-boot-starter-web")
implementation ("org.springframework.boot:spring-boot-starter-data-jpa")
implementation ("org.postgresql:postgresql")
testCompile("junit:junit")
}
application.properties
# Database
spring.datasource.url=jdbc:postgresql://localhost:5444/db?currentSchema=fms
spring.datasource.username=username
spring.datasource.password=password
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
The problem I am facing is when not using org.springframework.boot:spring-boot-starter-data-jpa dependency in my build.gradle file, I am able to successfully hit my controller from the browser.
But when I am using the org.springframework.boot:spring-boot-starter-data-jpa then the controller is not loaded in spring context and I am unable to hit the controller from my browser.
How do I use spring-data-jpa in my spring boot project containing exposed web sevices, please help !
Note : there is no error in logs, application starts successfully.
logs:
2019-06-10 09:52:11.348 INFO 15540 --- [ main] o.r.fms.documentmgmt.FMSApplication : Starting FMSApplication on abcd with PID 15540 (C:\Users\furquan.ahmed\Workspaces\fmsWorkspace\document-mgmt\bin\main started by furquan.ahmed in C:\Users\furquan.ahmed\Workspaces\fmsWorkspace\document-mgmt)
2019-06-10 09:52:11.354 INFO 15540 --- [ main] o.r.fms.documentmgmt.FMSApplication : No active profile set, falling back to default profiles: default
2019-06-10 09:52:12.200 INFO 15540 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-06-10 09:52:12.228 INFO 15540 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 13ms. Found 0 repository interfaces.
2019-06-10 09:52:13.083 INFO 15540 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$5149c32d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-06-10 09:52:14.106 INFO 15540 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-06-10 09:52:14.161 INFO 15540 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-06-10 09:52:14.162 INFO 15540 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-06-10 09:52:14.402 INFO 15540 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-06-10 09:52:14.402 INFO 15540 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2968 ms
2019-06-10 09:52:14.714 INFO 15540 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-06-10 09:52:18.002 INFO 15540 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-06-10 09:52:18.099 INFO 15540 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-06-10 09:52:18.267 INFO 15540 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.9.Final}
2019-06-10 09:52:18.268 INFO 15540 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-06-10 09:52:18.494 INFO 15540 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-06-10 09:52:19.060 INFO 15540 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect

If there's no direct need to explicitly state the basePackages for #EnableJpaRepositories and #EntityScan, I would suggest letting Spring find out the locations by means of auto-configuration, as all your classes are located in org.railway.fms.documentmgmt:
#SpringBootApplication
#EnableJpaRepositories
public class FMSApplication { ... }
Otherwise, try adding a #ComponentScan to state the location of Spring components:
#SpringBootApplication
#EnableJpaRepositories(basePackages = "org.railway.fms.documentmgmt.repository")
#EntityScan(basePackages= "org.railway.fms.documentmgmt.entities")
#ComponentScan(basePackages= "org.railway.fms.documentmgmt")
public class FMSApplication { ... }
Furthermore, if you do need to state the base package location, there's also the option to use basePackageClasses instead of basePackages, which is a type-safe alternative.

As you mentioned
The problem I am facing is when not using org.springframework.boot:spring-boot-starter-data-jpa dependency in my build.gradle file, I am able to successfully hit my controller from the browser.
But when I am using the org.springframework.boot:spring-boot-starter-data-jpa then the controller is not loaded in spring context and I am unable to hit the controller from my browser.
I think when you are adding org.springframework.boot:spring-boot-starter-data-jpa you may be forgetting to add db config in in application.properties
If I'm correct then add below properties in application.properties file and replace the values with specific to you db
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
in case you have already added these properties. Could you please provide logs and stack trace to see what errors are you getting.

Try to define below properties in your application.properties file.
server.servlet.context-path
spring.data.rest.base-path
Now access your controller mappings using the context-path and the rest repository mappings using rest.base-path.

Related

faced 'Spring Security & whitelabel Error 404' at the very first step

I just started making
Springboot starter project with gradle
first of all, i can't understand why i see security log-in page even when i set config permitAll
and secondly, i see 404 error after i log-in correctly
this is my SecurityConfig
package config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
//super.configure(http);
http.authorizeRequests()
.anyRequest().permitAll();
}
}
this is the controller
package notice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ApiNoticeController {
#GetMapping("/api/notice")
public String noticeSting() {
return "notice";
}
}
dependencies
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
testImplementation 'org.springframework.security:spring-security-test'
}
console
2022-03-23 18:50:34.733 INFO 27256 --- [ main] com.example.demo.PracticeApplication : Starting PracticeApplication using Java 17.0.1 on DESKTOP-JBB51IM with PID 27256 (C:\Users\user1\Desktop\CRUD\practice\bin\main started by user1 in C:\Users\user1\Desktop\CRUD\practice)
2022-03-23 18:50:34.740 INFO 27256 --- [ main] com.example.demo.PracticeApplication : No active profile set, falling back to 1 default profile: "default"
2022-03-23 18:50:36.429 INFO 27256 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-03-23 18:50:36.453 INFO 27256 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8 ms. Found 0 JPA repository interfaces.
2022-03-23 18:50:37.521 INFO 27256 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-03-23 18:50:37.538 INFO 27256 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-03-23 18:50:37.538 INFO 27256 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.58]
2022-03-23 18:50:37.773 INFO 27256 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-03-23 18:50:37.774 INFO 27256 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2922 ms
2022-03-23 18:50:38.067 INFO 27256 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-03-23 18:50:38.415 INFO 27256 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-03-23 18:50:38.508 INFO 27256 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-03-23 18:50:38.614 INFO 27256 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.5.Final
2022-03-23 18:50:39.009 INFO 27256 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-03-23 18:50:39.252 INFO 27256 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2022-03-23 18:50:39.781 INFO 27256 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-03-23 18:50:39.801 INFO 27256 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-03-23 18:50:39.866 WARN 27256 --- [ 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-23 18:50:40.609 INFO 27256 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: ****
2022-03-23 18:50:40.934 INFO 27256 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will not secure any request
2022-03-23 18:50:41.124 INFO 27256 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-23 18:50:41.145 INFO 27256 --- [ main] com.example.demo.PracticeApplication : Started PracticeApplication in 7.185 seconds (JVM running for 9.471)
2022-03-23 18:50:48.680 INFO 27256 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-03-23 18:50:48.680 INFO 27256 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-03-23 18:50:48.681 INFO 27256 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2022-03-23 18:50:49.157 WARN 27256 --- [nio-8080-exec-1] o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [397] milliseconds.
it worked well at first, returning URL "http://localhost:8080/api/notice" & String "notice"
but suddenly not working...
What I know and saw is that I used #RestController so i don't need html view resolver...
i also tried with configuration -
// super.configure(http);
super.configure(http);
both...didn't work
Sorry it was a stupid mistake.... as you can see in the package name, i set the package path wrong. thanks everybody for reading

Illegal use of #Table in a subclass of a SINGLE_TABLE hierarchy

I'm a newbie in Spring. I try to create a project with SOLID techniques but was faced with that error. Inheritance does not work in my application. Why inheritance does not work properly? Is inheritance allowed in Spring?
Text of Error:
2021-06-23 23:54:08.928 INFO 12984 --- [ restartedMain] hrms.northwind.NorthwindApplication : Starting NorthwindApplication using Java 15.0.2 on DESKTOP-87K40S0 with PID 12984 (C:\Users\90553\Desktop\Eclipse Projects\HRMS Project\target\classes started by 90553 in C:\Users\90553\Desktop\Eclipse Projects\HRMS Project)
2021-06-23 23:54:08.929 INFO 12984 --- [ restartedMain] hrms.northwind.NorthwindApplication : No active profile set, falling back to default profiles: default
2021-06-23 23:54:08.978 INFO 12984 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-06-23 23:54:08.978 INFO 12984 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-06-23 23:54:09.465 INFO 12984 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-06-23 23:54:09.512 INFO 12984 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 40 ms. Found 2 JPA repository interfaces.
2021-06-23 23:54:10.040 INFO 12984 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-06-23 23:54:10.052 INFO 12984 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-06-23 23:54:10.052 INFO 12984 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-06-23 23:54:10.130 INFO 12984 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-06-23 23:54:10.130 INFO 12984 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1152 ms
2021-06-23 23:54:10.203 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-06-23 23:54:10.367 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-06-23 23:54:10.458 INFO 12984 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-06-23 23:54:10.502 INFO 12984 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-06-23 23:54:10.619 INFO 12984 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-06-23 23:54:10.721 INFO 12984 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2021-06-23 23:54:11.047 WARN 12984 --- [ restartedMain] org.hibernate.cfg.AnnotationBinder : HHH000139: Illegal use of #Table in a subclass of a SINGLE_TABLE hierarchy: hrms.northwind.entities.concretes.Employer
2021-06-23 23:54:11.049 WARN 12984 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.ClassCastException: class org.hibernate.mapping.SingleTableSubclass cannot be cast to class org.hibernate.mapping.RootClass (org.hibernate.mapping.SingleTableSubclass and org.hibernate.mapping.RootClass are in unnamed module of loader 'app')
2021-06-23 23:54:11.050 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-06-23 23:54:11.053 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-06-23 23:54:11.057 INFO 12984 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-06-23 23:54:11.066 INFO 12984 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-06-23 23:54:11.084 ERROR 12984 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
Employer Class:
package hrms.northwind.entities.concretes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
#Entity(name="Employers")
#Table(name="Employers")
#Data
public class Employer extends Person {
#Id
#GeneratedValue
#Column(name="employer_id")
private int employerId;
#Column(name="company_name")
private String company_name;
#Column(name="website")
private String website;
#Column(name="phone_number")
private String phone_number;
#Column(name="password")
private String password;
public Employer(int personId, String name, String surname, String email, int employerId, String company_name, String website,
String phone_number, String password) {
super(personId, name, surname, email);
this.employerId = employerId;
this.company_name = company_name;
this.website = website;
this.phone_number = phone_number;
this.password = password;
}
}
Employer Dao:
package hrms.northwind.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import hrms.northwind.entities.concretes.Employer;
public interface EmployerDao extends JpaRepository<Employer,Integer>{
}
Employer Service:
package hrms.northwind.business.abstracts;
import java.util.List;
import org.springframework.stereotype.Service;
import hrms.northwind.entities.concretes.Employer;
#Service
public interface EmployerService {
List<Employer> getAll();
}
Employer Controller:
package hrms.northwind.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import hrms.northwind.business.abstracts.EmployerService;
import hrms.northwind.entities.concretes.Employer;
#RestController
#RequestMapping("/api/employers")
public class EmployerController {
private EmployerService employerService;
#Autowired
public EmployerController(EmployerService employerService) {
super();
this.employerService = employerService;
}
#GetMapping("/getall")
public List<Employer> getAll(){
return this.employerService.getAll();
}
}
Employer Table:
Employer Table
Any help?
Maybe is late for this answer
I think the problem comes from #Table. That annotation is optional when you want to specify an entity.
You could find better documented answer here
You can add this to your Employer class.
#Inheritance(strategy = InheritanceType.JOINED)
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#PrimaryKeyJoinColumn(name="employer_id",referencedColumnName = "person_id")

Resolving Singletons in Spring Boot Rest Controllers with Kotlin

I am new to Spring and Spring Boot and I played around with different ways how to resolve Beans. In my example I've got a Bean that should always be a singleton. What surprises me is that there seems to be a way where this bean is resolved as, I assume, "prototype".
Could anyone explain to me why it's not a singleton when it is resolved in the signature of the method showSingletonBeans?
#SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
#Service("stackSingletonBean")
// #Scope("singleton")
class MySingletonBean {
init {
println("Created MySingletonBean " + this.hashCode())
}
}
#RestController
class MyController {
#Autowired
// #Qualifier("singletonBean")
lateinit var memberSingletonBean: MySingletonBean
#Autowired
lateinit var singeltonFactory: ObjectFactory<MySingletonBean>
fun buildSingleton() : MySingletonBean {
return singeltonFactory.`object`
}
#Lookup
fun getSingletonInstance() : MySingletonBean? {
return null
}
#GetMapping("/")
fun showSingletonBeans(#Autowired stackSingletonBean: MySingletonBean) {
println("member " + memberSingletonBean.hashCode() )
println("stack " + stackSingletonBean.hashCode())
println("lookup:" + getSingletonInstance().hashCode())
println("factory: " + buildSingleton().hashCode())
}
}
The log looks like that:
2020-08-13 18:44:32.604 INFO 172175 --- [ main] com.example.demo.DemoApplicationKt : No active profile set, falling back to default profiles: default
2020-08-13 18:44:33.118 INFO 172175 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-13 18:44:33.124 INFO 172175 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-13 18:44:33.124 INFO 172175 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-13 18:44:33.164 INFO 172175 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-13 18:44:33.164 INFO 172175 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 528 ms
Created MySingletonBean 1747702724
2020-08-13 18:44:33.286 INFO 172175 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-13 18:44:33.372 INFO 172175 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-13 18:44:33.379 INFO 172175 --- [ main] com.example.demo.DemoApplicationKt : Started DemoApplicationKt in 1.011 seconds (JVM running for 1.24)
2020-08-13 18:44:37.341 INFO 172175 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-13 18:44:37.341 INFO 172175 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-13 18:44:37.344 INFO 172175 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms
Created MySingletonBean 562566586
member 1747702724
stack 562566586
lookup:1747702724
factory: 1747702724
Created MySingletonBean 389331797
member 1747702724
stack 389331797
lookup:1747702724
factory: 1747702724
Resolving controller method parameters is actually quite different mechanism. It has nothing to do with dependency injection and the #Autowired annotation: the annotation can be removed and it won't change the behavior.
Although #Autowired can technically be declared on individual method or constructor parameters since Spring Framework 5.0, most parts of the framework ignore such declarations. The only part of the core Spring Framework that actively supports autowired parameters is the JUnit Jupiter support in the spring-test module (see the TestContext framework reference documentation for details).
https://docs.spring.io/
In your case, the stackSingletonBean is instantiated by the ModelAttributeMethodArgumentResolver. It's not aware of the #Service annotation nor of its scope: it simply uses the default constructor on each request.
Model attributes are sourced from the model, or created using a default constructor and then added to the model.
Note that use of #ModelAttribute is optional — for example, to set its attributes. By default, any argument that is not a simple value type( as determined by BeanUtils#isSimpleProperty) and is not resolved by any other argument resolver is treated as if it were annotated with #ModelAttribute. Web on Reactive Stack

How to move Zuul gateway configurations to configuration server

I'm starting out with microservices architecture and spring cloud.
I'm trying to get configurations for my Spring Zuul Gateway from the spring configuration server.
I've added below properties in bootstrap.properties file of the gateway service:
spring.application.name=api-gateway
spring.cloud.config.uri=http://localhost:8888
spring.profiles.active=dev
Even though these properties work for all other services, for the gateway they do not work.
The annotations I'm using for the gateway are:
#EnableZuulProxy
#EnableDiscoveryClient
#SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
The annotation for other services is only:
#SpringBootApplication
My configuration server has a connected git repository with a file: api-gateway-dev.properties
logs of gateway:
:: Spring Boot :: (v2.3.0.M4)
2020-04-17 21:42:39.983 INFO 10340 --- [ restartedMain]
c.nyo.apigateway.ApiGatewayApplication : The following profiles are
active: dev 2020-04-17 21:42:41.926 WARN 10340 --- [ restartedMain]
o.s.boot.actuate.endpoint.EndpointId : Endpoint ID
'service-registry' contains invalid characters, please migrate to a
valid format. 2020-04-17 21:42:41.969 WARN 10340 --- [
restartedMain] o.s.boot.actuate.endpoint.EndpointId : Endpoint ID
'hystrix.stream' contains invalid characters, please migrate to a
valid format. 2020-04-17 21:42:42.240 INFO 10340 --- [
restartedMain] o.s.cloud.context.scope.GenericScope : BeanFactory
id=a11a283e-7de6-3470-b177-65c08eab7398 2020-04-17 21:42:43.859 INFO
10340 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer :
Tomcat initialized with port(s): 8765 (http) 2020-04-17 21:42:43.880
INFO 10340 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
logs of a service that is getting configurations:
:: Spring Boot :: (v2.3.0.M4)
2020-04-17 21:54:01.414 INFO 5180 --- [ restartedMain]
c.c.c.ConfigServicePropertySourceLocator : Fetching config from server
at : http://localhost:8888 2020-04-17 21:54:04.184 INFO 5180 --- [
restartedMain] c.c.c.ConfigServicePropertySourceLocator : Located
environment: name=users-service, profiles=[dev], label=null,
version=244114f5a11aa7d4a0acb5750ddad144f7de1be5, state=null
2020-04-17 21:54:04.186 INFO 5180 --- [ restartedMain]
b.c.PropertySourceBootstrapConfiguration : Located property source:
[BootstrapPropertySource {name='bootstrapProperties-configClient'},
BootstrapPropertySource
{name='bootstrapProperties-https://my-user#bitbucket.org/my-user/configs.git/users-service-dev.properties'},
BootstrapPropertySource
{name='bootstrapProperties-https://my-user#bitbucket.org/my-user/configs.git/users-service.properties'}]
2020-04-17 21:54:04.197 INFO 5180 --- [ restartedMain]
c.n.U.UsersServiceApplication : The following profiles are
active: dev
Is it logical to make gateway configuration dynamic?
Why don't I get the configuration from the configuration server?
Found the problem. I was missing:
implementation 'org.springframework.cloud:spring-cloud-starter-config'
in my build.gradle file dependencies

Spring boot initialization is not reading from hibernate.properties

I am trying to create a very basic Spring Boot web application, using Spring Boot, Hibernate and MySQL. The basic objective is to convert a complex JSON to a cascaded set of POJOs and persist in the database. In hibernate.properties I configured Mysql5InnodbDialect, but the initialization goes for a different dialect. Hope the following log is enough for an explanation, nevertheless would post if more information is needed.
2019-04-06 10:25:36.448 INFO 2256 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2019-04-06 10:25:36.448 INFO 2256 --- [ main] org.hibernate.cfg.Environment : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.hbm2ddl.auto=UPDATE, hibernate.format_sql=true}
2019-04-06 10:25:36.511 INFO 2256 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-04-06 10:25:36.573 INFO 2256 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Can you be trying to scan your application properties file in Spring Boot?
#EnableAutoConfiguration
#SpringBootApplication(scanBasePackages={"com.virus.shopingcart.*"})
#EnableJpaRepositories("com.virus.shopingcart.*")
#ComponentScan("com.virus.shopingcart.*")
#PropertySource("classpath:application.properties")
public class ShopingBoot extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ShopingBoot.class, args);
}
}

Resources