Connect limits service to spring cloud config server failed - spring-boot

i would like ask your help regarding the above question.Now I am trying to connect application (SpringCloudConfigServer) with another application (Limits-service), Limits-service application have to pick the SpringCloudConfigServer properties file. when I hit http://localhost:8080/limits i need to get oupput like {"maximum":888,"minimum":8} but im getting {"maximum":999,"minimum":99}
this is my stack trace
2020-04-29 22:51:23.740 INFO 2016 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at :` http://localhost:8888
2020-04-29 22:51:25.063 INFO 2016 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Connect Timeout Exception on Url - http://localhost:8888. Will be trying the next url if available
2020-04-29 22:51:25.074 WARN 2016 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/limits-service/dev": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
2020-04-29 22:51:25.074 INFO 2016 --- [ restartedMain] c.i.m.l.LimitsServiceApplication : The following profiles are active: dev
2020-04-29 22:51:27.792 INFO 2016 --- [ restartedMain] o.s.cloud.context.scope.GenericScope : BeanFactory id=fe72d2a0-4692-3641-b317-8a12c5b9eb59
2020-04-29 22:51:29.065 INFO 2016 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-04-29 22:51:29.099 INFO 2016 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-04-29 22:51:29.099 INFO 2016 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33]
2020-04-29 22:51:29.349 INFO 2016 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-04-29 22:51:29.349 INFO 2016 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4166 ms
2020-04-29 22:51:30.477 INFO 2016 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-04-29 22:51:31.571 INFO 2016 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-04-29 22:51:31.941 INFO 2016 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-04-29 22:51:32.269 INFO 2016 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-04-29 22:51:32.627 INFO 2016 --- [ restartedMain] c.i.m.l.LimitsServiceApplication : Started LimitsServiceApplication in 12.155 seconds (JVM running for 14.055)
2020-04-29 22:51:39.114 INFO 2016 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-04-29 22:51:39.115 INFO 2016 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-04-29 22:51:39.151 INFO 2016 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 35 ms
here is my limits service code
package com.in28minutes.microservices.limitsservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LimitsServiceApplication {
public static void main(String[] args) {
SpringApplication.run(LimitsServiceApplication.class, args);
}
}
`controller
package com.in28minutes.microservices.limitsservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.in28minutes.microservices.limitsservice.bean.LimitConfiguration;
#RestController
public class LimitsConfigurationController {
#Autowired
private Configuration configuration;
#GetMapping("/limits")
public LimitConfiguration retrieveLimitsFromConfigurations() {
return new LimitConfiguration(configuration.getMaximum(),
configuration.getMinimum());
}
}
component class
package com.in28minutes.microservices.limitsservice;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
#ConfigurationProperties("limits-service")
public class Configuration {
private int minimum;
private int maximum;
public int getMinimum() {
return minimum;
}
public int getMaximum() {
return maximum;
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
}
Bean class
package com.in28minutes.microservices.limitsservice.bean;
public class LimitConfiguration {
private int maximum;
private int minimum;
protected LimitConfiguration() {
}
public LimitConfiguration(int maximum, int minimum) {
super();
this.maximum = maximum;
this.minimum = minimum;
}
public int getMaximum() {
return maximum;
}
public int getMinimum() {
return minimum;
}
}
bootstrap.properties
spring.application.name=limits-service
spring.cloud.config.server.uri=http://localhost:8888
/git-localconfig-repo/limits-service.properties
limits-service.minimum=8
limits-service.maximum=888
please help me how to fix this

It looks like your config server call fails. That is why you are not able to load properties from config server but from your service local config file
Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/limits-service/dev": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
2020-04-29 22:51:25.074 INFO 2016 --- [ restartedMain] c.i.m.l.LimitsServiceApplication : The following profiles are active: dev

In your /git-localconfig-repo/limits-service.properties
add spring.cloud.config.server.git.uri=file:/git-localconfig-repo/limits-service

Related

I'm still getting a Whitelabel error even though there is no error in my IDE

I'm still getting an error even though there is no error in my IDE
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#SpringBootApplication
#RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#GetMapping
public List<String> hello(){
return List.of("hello", "world");
}
}
:: Spring Boot :: (v3.0.0-SNAPSHOT)
2022-08-26T08:32:07.263+08:00 INFO 10580 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 17.0.4.1 on DESKTOP-53LAED9 with PID 10580 (C:\Users\Larty\Desktop\Programming Softwares\Springsss\demo\demo\target\classes started by Larty in C:\Users\Larty\Desktop\Programming Softwares\Springsss\demo\demo)
2022-08-26T08:32:07.276+08:00 INFO 10580 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
2022-08-26T08:32:10.093+08:00 INFO 10580 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8060 (http)
2022-08-26T08:32:10.120+08:00 INFO 10580 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-08-26T08:32:10.121+08:00 INFO 10580 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.0.22]
2022-08-26T08:32:10.428+08:00 INFO 10580 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-08-26T08:32:10.434+08:00 INFO 10580 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3010 ms
2022-08-26T08:32:11.412+08:00 INFO 10580 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8060 (http) with context path ''
2022-08-26T08:32:11.435+08:00 INFO 10580 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 5.245 seconds (process running for 6.304)
More info that caused the error:
I change my port to 8060 cause I'm getting an error from 8080.
Try specify a path:
#GetMapping("/")
// or this syntax
#GetMapping(path = "/")
If you want to have more control over request mapping, you can take a look at #RequestMapping annotation.
BTW, the port is running at 8060, accessing http://localhost:8060 should return the list of Strings.

POST request 404 not found

Hello fellow programmers, I'm having trouble solving the 404 error in postman when I request the POST method.
{
"timestamp": "2022-06-01T03:17:33.459+00:00",
"status": 404,
"error": "Not Found",
"path": "/parking-spot"
}
I'm creating an API that does the parking control with Spring Boot. The program does not show any errors when I run the application.
2022-06-01 00:37:35.226 INFO 1720 --- [ main] c.a.p.ParkingControlApplication : Starting ParkingControlApplication using Java 17.0.2 on DESKTOP-7GPB86C with PID 1720 (C:\Users\sergio\Documents\Projetos\Spring boot\Projeto 01\parking-control\Parking Control\target\classes started by sergio in C:\Users\sergio\Documents\Projetos\Spring boot\Projeto 01\parking-control\Parking Control)
2022-06-01 00:37:35.228 INFO 1720 --- [ main] c.a.p.ParkingControlApplication : No active profile set, falling back to 1 default profile: "default"
2022-06-01 00:37:35.558 INFO 1720 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-06-01 00:37:35.568 INFO 1720 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 3 ms. Found 0 JPA repository interfaces.
2022-06-01 00:37:36.078 INFO 1720 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-06-01 00:37:36.091 INFO 1720 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-06-01 00:37:36.092 INFO 1720 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-01 00:37:36.177 INFO 1720 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-06-01 00:37:36.177 INFO 1720 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 908 ms
2022-06-01 00:37:36.275 INFO 1720 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-06-01 00:37:36.307 INFO 1720 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.9.Final
2022-06-01 00:37:36.421 INFO 1720 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-06-01 00:37:36.493 INFO 1720 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-06-01 00:37:36.634 INFO 1720 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-06-01 00:37:36.654 INFO 1720 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2022-06-01 00:37:36.821 INFO 1720 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-06-01 00:37:36.829 INFO 1720 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-06-01 00:37:36.864 WARN 1720 --- [ 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-06-01 00:37:37.106 INFO 1720 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-06-01 00:37:37.113 INFO 1720 --- [ main] c.a.p.ParkingControlApplication : Started ParkingControlApplication in 2.176 seconds (JVM running for 2.494)
2022-06-01 00:38:30.217 INFO 1720 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-06-01 00:38:30.217 INFO 1720 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-06-01 00:38:30.218 INFO 1720 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Aplication:
package com.api.parkingcontrol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#SpringBootApplication
#RestController
#ComponentScan("ParkingSpotController")
#EnableJpaRepositories("ParkingSpotRepository")
#EntityScan("ParkingSpotRepository")
public class ParkingControlApplication {
public static void main(String[] args) {
SpringApplication.run(ParkingControlApplication.class, args);
}
#GetMapping("/")
public String index() {
return "Olá Mundo";
}
}
Controller:
package com.api.parkingcontrol.controllers;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.api.parkingcontrol.dtos.ParkingSpotDto;
import com.api.parkingcontrol.models.ParkingSpotModel;
import com.api.parkingcontrol.services.ParkingSpotService;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping(value = "/parking-spot")
public class ParkingSpotController {
final ParkingSpotService parkingSpotService;
public ParkingSpotController(ParkingSpotService parkingSpotService) {
this.parkingSpotService = parkingSpotService;
}
#PostMapping("/parking-spot")
#ResponseBody
public ResponseEntity<Object> saveParkingSpot(#RequestBody #Valid ParkingSpotDto parkingSpotDto) {
if (parkingSpotService.existByLicensePlateCar(parkingSpotDto.getLicensePlateCar())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("Conflict: License Plate Car is already in use!");
}
if (parkingSpotService.existsByParkingSpotNumber(parkingSpotDto.getParkingSpotNumber())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("Conflict: Parking Spot already in use!");
}
if (parkingSpotService.existsByApartmentAndBlock(parkingSpotDto.getApartament(), parkingSpotDto.getBlock())) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body("Conflict: Parking Spot already registered for this apartment/block!");
}
var parkingSpotModel = new ParkingSpotModel();
BeanUtils.copyProperties(parkingSpotDto, parkingSpotModel);
parkingSpotModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(parkingSpotService.save(parkingSpotModel));
}
#GetMapping
public ResponseEntity<List<ParkingSpotModel>> getAllParkingSpots() {
return ResponseEntity.status(HttpStatus.OK).body(parkingSpotService.findAll());
}
}
Service:
package com.api.parkingcontrol.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.api.parkingcontrol.models.ParkingSpotModel;
import com.api.parkingcontrol.repositories.ParkingSpotRepository;
#Service
public class ParkingSpotService {
final ParkingSpotRepository parkingSpotRepository;
/*Constructor do Repository*/
public ParkingSpotService(ParkingSpotRepository parkingSpotRepository) {
this.parkingSpotRepository = parkingSpotRepository;
}
#Transactional
public Object save(ParkingSpotModel parkingSpotModel) {
return parkingSpotRepository.save(parkingSpotModel);
}
public boolean existByLicensePlateCar(String licensePlateCar) {
return parkingSpotRepository.existByLicensePlateCar(licensePlateCar);
}
public boolean existsByParkingSpotNumber(String parkingSpotNumber) {
return parkingSpotRepository.existsByParkingSpotNumber(parkingSpotNumber);
}
public boolean existsByApartmentAndBlock(String apartament, String block) {
return parkingSpotRepository.existsByApartmentAndBlock(apartament, block);
}
public List<ParkingSpotModel> findAll (){
return parkingSpotRepository.findAll();
}
}
Am I missing something?
The problem is that in your controller you have
1)
#RequestMapping(value = "/parking-spot")
public class ParkingSpotController
and
2)
#PostMapping("/parking-spot")
#ResponseBody
public ResponseEntity<Object> saveParkingSpot
This means that your endpoint will be available by the path: /parking-spot/parking-spot

How to inject List of String arrays in spring from properties file?

how to create a nested arrays in list in application properties, and insert it as a value?
#Value("${LIST_OF_NESTED_ARRAYS}")
List<String[]> list;
Yes, By using Spring Expression Language it can be achieved.
Code:
package com.test.listofarray;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.extern.slf4j.Slf4j;
#SpringBootApplication
#Slf4j
public class TestApplication implements CommandLineRunner {
#Value("#{'${LIST_OF_NESTED_ARRAYS}'.split(';')}")
private List<String[]> list;
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
list.forEach(array -> log.info("array ----> {}", Arrays.toString(array)));
}
}
application.properties
LIST_OF_NESTED_ARRAYS=India,USA,Brazil;Asia,Africa
use semi-column(;) to separate the values of each array in the above property and give the same semi-column(;) in the split function inside #value annotation.
Verify the output of the injected list in the below output log.
Output:
2021-11-01 17:48:39.105 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : No active profile set, falling back to default profiles: default
2021-11-01 17:48:42.184 INFO 11352 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-11-01 17:48:42.206 INFO 11352 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-11-01 17:48:42.207 INFO 11352 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.54]
2021-11-01 17:48:42.411 INFO 11352 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-11-01 17:48:42.411 INFO 11352 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3235 ms
2021-11-01 17:48:45.139 INFO 11352 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'
2021-11-01 17:48:45.256 INFO 11352 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-11-01 17:48:45.285 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : Started RetryApplication in 6.946 seconds (JVM running for 7.648)
2021-11-01 17:48:45.397 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : array ----> [India, USA, Brazil]
2021-11-01 17:48:45.400 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : array ----> [Asia, Africa]
2021-11-01 17:49:03.860 INFO 11352 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-11-01 17:49:03.861 INFO 11352 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-11-01 17:49:03.862 INFO 11352 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
If you are using application.yml you can do it as follows:
yourProperty:
- - "Array1 - String1"
- "Array1 - String2"
- - "Array2 - String1"
- "Array2 - String2"

Using different packages for Controllers when using in Spring Boot

I am new in Spring boot.I trying to access the controller url but i didn't get any response from them.
We are followed spring boot project structure as per document.
I have used componentscan annotation and added scanBasePackageClasses in SpringBootApplication annotation.But still same.
HomeController :-
package com.main.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/home",method=RequestMethod.GET)
public String home() {
System.out.println("home");
return "home";
}
}
GAppsApplication.java:-
package com.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.main.controllers.HomeController;
#ComponentScan({"com.main.controllers"})
#SpringBootApplication(scanBasePackageClasses={HomeController.class})
public class GAppsApplication {
public static void main(String[] args) {
SpringApplication.run(GAppsApplication.class, args);
}
}
For your reference i shared below logs
logs:-
2018-08-28 08:26:16.404 INFO 8172 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#58b9d6, org.springframework.security.web.context.SecurityContextPersistenceFilter#525747, org.springframework.security.web.header.HeaderWriterFilter#1638752, org.springframework.security.web.csrf.CsrfFilter#324c61, org.springframework.security.web.authentication.logout.LogoutFilter#14a6743, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#12d6ce4, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#1837d01, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#eda2d2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#4a5109, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#4bb38c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#12205be, org.springframework.security.web.session.SessionManagementFilter#2e4343, org.springframework.security.web.access.ExceptionTranslationFilter#1a81a58, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#12e7437]
2018-08-28 08:26:16.558 INFO 8172 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-08-28 08:26:16.592 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-08-28 08:26:16.594 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-08-28 08:26:16.600 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-08-28 08:26:16.638 INFO 8172 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-08-28 08:26:16.642 INFO 8172 --- [ restartedMain] c.main.GAppsApplication : Started GAppsApplication in 5.153 seconds (JVM running for 5.734)
2018-08-28 08:27:11.961 INFO 8172 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-08-28 08:27:11.961 INFO 8172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-08-28 08:27:11.980 INFO 8172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms
Change your controller to like below :
#RestController
#RequestMapping("/home")
public class HomeController {
#GetMapping
public String home() {
System.out.println("home");
return "home";
}
}
As your base package is com.main, so any package within com.main will automatically be scanned.
You don't need to put any special annotation to scan.

Why Spring Boot Application logs that it started twice after adding spring-cloud-bus dependency

This is simple code in my Spring boot application:
package com.maxxton.SpringBootHelloWorld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}
And a ApplicationListener class to listen to ApplicationEvent:
package com.maxxton.SpringBootHelloWorld;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
#Component
public class Test implements ApplicationListener {
#Override
public void onApplicationEvent(ApplicationEvent event) {
if (event.getClass().getSimpleName().equals("ApplicationReadyEvent")) {
System.out.println("-------------------------------------");
System.out.println(event.getClass().getSimpleName());
System.out.println("-------------------------------------");
}
}
}
build.gradle contains these dependencies:
dependencies {
compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter')
compile("org.springframework.cloud:spring-cloud-starter")
compile("org.springframework.cloud:spring-cloud-starter-security")
compile("org.springframework.cloud:spring-cloud-starter-eureka")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Now, when I run this spring boot application, I see this log printed twice:
[main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in ... seconds (JVM running for ...)
Usually, this log get printed only once, but it get printed twice if I add these dependencies:
compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
This is complete log:
2017-11-17 15:44:07.372 INFO 5976 --- [ main] o.s.c.support.GenericApplicationContext : Refreshing org.springframework.context.support.GenericApplicationContext#31c7c281: startup date [Fri Nov 17 15:44:07 IST 2017]; root of context hierarchy
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:07.403 INFO 5976 --- [ main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in 1.19 seconds (JVM running for 10.231)
2017-11-17 15:44:09.483 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:09.492 INFO 5976 --- [ main] o.s.integration.channel.DirectChannel : Channel 'a-bootiful-client.springCloudBusOutput' has 1 subscriber(s).
2017-11-17 15:44:09.493 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'a-bootiful-client.errorChannel' has 1 subscriber(s).
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147482647
2017-11-17 15:44:09.539 INFO 5976 --- [ main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, bound to: springCloudBus
2017-11-17 15:44:11.562 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:13.587 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare queue: Queue [name=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, durable=false, autoDelete=true, exclusive=true, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:15.611 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare binding: Binding [destination=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, exchange=springCloudBus, routingKey=#], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.a.i.AmqpInboundChannelAdapter : started inbound.springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {message-handler:inbound.springCloudBus.default} as a subscriber to the 'bridge.springCloudBus' channel
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started inbound.springCloudBus.default
2017-11-17 15:44:17.663 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2017-11-17 15:44:17.714 INFO 5976 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:17.717 INFO 5976 --- [ main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in 20.131 seconds (JVM running for 20.545)
As you can see, ApplicationReadyEvent is happening twice.
Why is this happening?
Is there any way to avoid this?
spring-cloud-bus uses spring-cloud-stream which puts the binder in a separate boot child application context.
You should make your event listener aware of the application context it is running in. You can also use generics to select the event type you are interested in...
#Component
public class Test implements ApplicationListener<ApplicationReadyEvent>,
ApplicationContextAware {
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Override
public void onApplicationEvent(ApplicationReadyEvent event) {
if (event.getApplicationContext().equals(this.applicationContext)) {
System.out.println("-------------------------------------");
System.out.println(event.getClass().getSimpleName());
System.out.println("-------------------------------------");
}
}
}
Are u using multiple binders rabbitmq configuration in your application.yml/.xml ?
If it's a yes, then u can try to exclude RabbitAutoConfiguration.
#EnableDiscoveryClient
#EnableAutoConfiguration(exclude = {RabbitAutoConfiguration.class})
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}

Resources