JUnit Spring Boot Application - Could not autowire fields - java

I have small app written with JHipster code generator with Spring Boot on back-end.
For my app I'm trying to write some simple unit/integration tests but I have an error: Could not autowire. No beans of <type> found. I'm using IntelliJ IDE, latest version. Here is my piece of code:
package com.logate.adminpanel.web.rest;
import com.logate.adminpanel.CrmScoringApp; import
com.logate.adminpanel.repository.CityRepository; import
com.logate.adminpanel.service.CityService; import org.junit.Test;
import org.junit.runner.RunWith; import
org.springframework.boot.test.SpringApplicationConfiguration; import
org.springframework.test.context.ContextConfiguration; import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.inject.Inject;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = CrmScoringApp.class)
#WebAppConfiguration
public class CityRestTest {
#Inject
private CityService cityService;
#Inject
private CityRepository cityRepository;
#Test
public void test()
{
Assert.isNull(null);
}
}
I can't figure it out what is the problem here.
Here is my boot application class:
package com.logate.adminpanel;
import com.logate.adminpanel.config.Constants;
import com.logate.adminpanel.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
#ComponentScan
#EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class })
#EnableConfigurationProperties({ JHipsterProperties.class, LiquibaseProperties.class })
public class CrmScoringApp {
private static final Logger log = LoggerFactory.getLogger(CrmScoringApp.class);
#Inject
private Environment env;
/**
* Main method, used to run the application.
*
* #param args the command line arguments
* #throws UnknownHostException if the local host name could not be resolved into an address
*/
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(CrmScoringApp.class);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
addDefaultProfile(app, source);
Environment env = app.run(args).getEnvironment();
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://127.0.0.1:{}\n\t" +
"External: \thttp://{}:{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"));
}
/**
* If no profile has been configured, set by default the "dev" profile.
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active") &&
!System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
/**
* Initializes admin_panel.
* <p>
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on http://jhipster.github.io/profiles/.
*/
#PostConstruct
public void initApplication() {
if (env.getActiveProfiles().length == 0) {
log.warn("No Spring profile configured, running with default configuration");
} else {
log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! " +
"It should not run with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! " +
"It should not run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
}
}
Here is city repository class:
package com.logate.adminpanel.repository;
import com.logate.adminpanel.domain.City;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the City entity.
*/
public interface CityRepository extends JpaRepository<City,Long> {
}
and here is city service class:
package com.logate.adminpanel.service;
import com.logate.adminpanel.domain.City;
import com.logate.adminpanel.repository.CityRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
/**
* Service Implementation for managing City.
*/
#Service
#Transactional
public class CityService {
private final Logger log = LoggerFactory.getLogger(CityService.class);
#Inject
private CityRepository cityRepository;
/**
* Save a city.
*
* #param city the entity to save
* #return the persisted entity
*/
public City save(City city) {
log.debug("Request to save City : {}", city);
City result = cityRepository.save(city);
return result;
}
#Transactional(readOnly = true)
public Page<City> findAll(Pageable pageable) {
log.debug("Request to get all Cities");
Page<City> result = cityRepository.findAll(pageable);
return result;
}
#Transactional(readOnly = true)
public City findOne(Long id) {
log.debug("Request to get City : {}", id);
City city = cityRepository.findOne(id);
return city;
}
public void delete(Long id) {
log.debug("Request to delete City : {}", id);
cityRepository.delete(id);
}
}
Stack trace:
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 30.66 sec <<< FAILURE! - in com.logate.adminpanel.web.rest.CityResourceIntTest
firstTest(com.logate.adminpanel.web.rest.CityResourceIntTest) Time elapsed: 0.018 sec <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDeleg ate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplication Context(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionL istener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(Te stContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest (SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Console error link: https://jpst.it/OJM6
Does anyone have an idea? Thank you in advance.

Your exception is caused by: java.lang.IllegalStateException: Tomcat connector in failed state. Usually it occurs when port used by tomcat is already in use. Try to change server.port in src/test/resources/config/application.yml file

your stackstrace is telling your com.logate.adminpanel.web.rest.CityResourceIntTest test is failing, not your CityRestTest.
If you want to have your tests be available to gradle test (which is very recommended if you're using CI/CD systems), the class names have to follow a nameconvention, containing "XXXIntTest" or "XXXUnitTest"...
I would look to your CityResourceIntTest, since the failure is there...and rename your rest test to the proper nameconvention.

Related

Configuration in Resilience4J CircuitBreaker not working

I'm using a circuit breaker of Resilience4J and I need to ignore some custom exceptions so I need to change the default configuration. I'm working with microservices so I have a microservice connected to a database which have some basic requests like get by id and I also have an edge service which use these requests. I need, for example, if the id doesn't exist, the microservice throws a custom exception and the circuitbreaker doesn't open in this case.
Microservice with the database:
Get request
#GetMapping("/sales-rep/{id}")
#ResponseStatus(HttpStatus.OK)
public SalesRepDTO getSalesRep(#PathVariable Integer id) {
return salesRepService.getSalesRep(id);
}
Service
public SalesRepDTO getSalesRep(Integer id) {
if(salesRepRepository.existsById(id)) {
SalesRep salesRep = salesRepRepository.findById(id).get();
return new SalesRepDTO(salesRep.getId(), salesRep.getName());
} else {
throw new SalesRepNotFoundException("Sales rep not found");
}
}
Edge service:
Service
import com.ironhack.manageAllservice.client.AccountClient;
import com.ironhack.manageAllservice.client.LeadClient;
import com.ironhack.manageAllservice.client.SalesRepClient;
import com.ironhack.manageAllservice.controller.dtos.*;
import com.ironhack.manageAllservice.controller.dtos.report.OpportunityBySalesRepDTO;
import com.ironhack.manageAllservice.controller.dtos.report.ReportDTO;
import com.ironhack.manageAllservice.service.exceptions.SalesRepNotFoundException;
import com.ironhack.manageAllservice.controller.dtos.report.*;
import com.ironhack.manageAllservice.service.interfaces.IManageAllService;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
#Service
public class ManageAllService implements IManageAllService {
#Autowired
private CircuitBreakerFactory circuitBreakerFactory;
#Bean
public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() {
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(1000))
.slidingWindowSize(2)
.ignoreExceptions(SalesRepNotFoundException.class)
.build();
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofSeconds(4))
.build();
return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.circuitBreakerConfig(circuitBreakerConfig)
.timeLimiterConfig(timeLimiterConfig)
.build());
}
public SalesRepDTO getSalesRepById(Integer id) {
CircuitBreaker circuitBreaker = circuitBreakerFactory.create("salesRep-service");
SalesRepDTO salesRepDTO = circuitBreaker.run(()->salesRepClient.getSalesRep(id),
throwable -> postSalesRepFallBack());
return salesRepDTO;
}
SalesRepNotFoundException.class is the exception I want to ignore, but the circuitbreaker isn't changing the configuration. Any suggestion?
I suggest that you have a look at our Spring Boot 2 starter: https://resilience4j.readme.io/docs/getting-started-3
Our Spring Boot starter allows you to extract the configuration into the config file and use annotations.

How to configure jhipster application

I am new to jhipster. I generated a project with the terminal jhipster command. I have a gateway service, upon trying to start the application I am getting these errors, the funny thing is I did not modify anything just out of box this happened. I have java 15, :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayResource' defined in file : Unable to resolve Configuration with the provided Issuer of "http://localhost:9080/auth/realms/jhipster"
this is my gateway class:
package com.moniesta.admin.web.rest;
import com.moniesta.admin.web.rest.vm.RouteVM;
import java.util.ArrayList;
import java.util.List;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import reactor.core.publisher.Flux;
import org.springframework.http.*;
import org.springframework.security.access.annotation.Secured;
import com.moniesta.admin.security.AuthoritiesConstants;
import org.springframework.web.bind.annotation.*;
/**
* REST controller for managing Gateway configuration.
*/
#RestController
#RequestMapping("/api/gateway")
public class GatewayResource {
private final RouteLocator routeLocator;
private final DiscoveryClient discoveryClient;
#Value("${spring.application.name}")
private String appName;
public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
this.routeLocator = routeLocator;
this.discoveryClient = discoveryClient;
}
/**
* {#code GET /routes} : get the active routes.
*
* #return the {#link ResponseEntity} with status {#code 200 (OK)} and with body the list of routes.
*/
#GetMapping("/routes")
#Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<List<RouteVM>> activeRoutes() {
Flux<Route> routes = routeLocator.getRoutes();
List<RouteVM> routeVMs = new ArrayList<>();
routes.subscribe(route -> {
RouteVM routeVM = new RouteVM();
// Manipulate strings to make Gateway routes look like Zuul's
String predicate = route.getPredicate().toString();
String path = predicate.substring(predicate.indexOf("[") + 1, predicate.indexOf("]"));
routeVM.setPath(path);
String serviceId = route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase();
routeVM.setServiceId(serviceId);
// Exclude gateway app from routes
if (!serviceId.equalsIgnoreCase(appName)) {
routeVM.setServiceInstances(discoveryClient.getInstances(serviceId));
routeVMs.add(routeVM);
}
});
return ResponseEntity.ok(routeVMs);
}
}

Spring Cloud Contract can not produce json in producer side

I want to write a contract using spring cloud contract in producer API.
My controller looks like :
#PostMapping(value = "/employee")
public ResponseEntity<Employee> getEmployee(#RequestBody Request employeeRequest) {
Optional<Employee> employee = employeeService.getEmployee(employeeRequest);
if(employee.isPresent()){
return ResponseEntity.status(HttpStatus.OK).
contentType(MediaType.APPLICATION_JSON).body(employee.get());
}else{
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Request class :
#Setter
#Getter
public class Request {
private Integer id;
}
Response (Employee) class :
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
public class Employee {
public Integer id;
public String fname;
public String lname;
public Double salary;
public String gender;
}
Dsl written in groovy :
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'POST'
url '/employee'
headers {
contentType(applicationJson())
}
body(
id : 25
)
}
response {
status 200
headers {
contentType(applicationJson())
}
body("""
{
"id":25,
"fname":"sara",
"lname":"ahmadi",
"salary":"25000.00",
"gender":"F"
}
""")
}
}
Plugin in pom.xml :
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>2.2.3.RELEASE</version>
<extensions>true</extensions>
<configuration>
<baseClassForTests>example.co.ir.contractproducer.BaseTestClass</baseClassForTests>
<testFramework>JUNIT5</testFramework>
</configuration>
</plugin>
And BaseTestClass :
import io.restassured.config.EncoderConfig;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import io.restassured.module.mockmvc.config.RestAssuredMockMvcConfig;
import isc.co.ir.contractproducer.controller.EmployeeController;
import isc.co.ir.contractproducer.model.Employee;
import isc.co.ir.contractproducer.model.Request;
import isc.co.ir.contractproducer.service.EmployeeService;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder;
import java.util.Optional;
#SpringBootTest
public class BaseTestClass {
#Autowired
private EmployeeController employeeController;
#MockBean
private EmployeeService employeeService;
#BeforeEach
public void setup(){
Employee employee2=new Employee(25,"Adam","Brown",25000.0,"F");
Request request = new Request();
request.setId(25);
Mockito.when(employeeService.getEmployee(request)).thenReturn(Optional.of(employee2));
EncoderConfig encoderConfig = new EncoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false);
RestAssuredMockMvc.config = new RestAssuredMockMvcConfig().encoderConfig(encoderConfig);
StandaloneMockMvcBuilder standaloneMockMvcBuilder
= MockMvcBuilders.standaloneSetup(employeeController);
RestAssuredMockMvc.standaloneSetup(standaloneMockMvcBuilder);
}
}
Generated test class:
import isc.co.ir.contractproducer.BaseTestClass;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import io.restassured.response.ResponseOptions;
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*;
#SuppressWarnings("rawtypes")
public class ContractVerifierTest extends BaseTestClass {
#Test
public void validate_shouldReturnEmployee() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"id\":25}");
// when:
ResponseOptions response = given().spec(request)
.post("/employee");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['id']").isEqualTo(25);
assertThatJson(parsedJson).field("['fname']").isEqualTo("sara");
assertThatJson(parsedJson).field("['lname']").isEqualTo("ahmadi");
assertThatJson(parsedJson).field("['salary']").isEqualTo("25000.00");
assertThatJson(parsedJson).field("['gender']").isEqualTo("F");
}
}
Now when I build the project I get this error :
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.469 s <<< FAILURE! - in example.co.ir.contractproducer.ContractVerifierTest
[ERROR] validate_shouldReturnEmployee Time elapsed: 0.607 s <<< FAILURE!
org.opentest4j.AssertionFailedError:
Expecting:
<500>
to be equal to:
<200>
but was not.
When I build project using Junit4 everything is work fine but while using Junit5 I had this problem.
How can I fix this problem?
Please remove #SpringBootTest and use RestAssuredMockMvc.standaloneSetup or leave #SpringBootTest, inject WebApplicationContext and use RestAssuredMockMvc.webAppContextSetup(context)

Spring is not running my #Scheduled(cron = "0,30 * * * * *")

Following is code
I am using spring.boot.version 1.4.1.RELEASE now
Nothing is printed when I start the server
I am using #Scheduled annotation to run a cron job but It never starts
Same code works fine if I create new project and use following classes
Please suggest what can possibly go wrong ?
package com.equilar.bsp;
import java.util.TimeZone;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.amazonaws.http.IdleConnectionReaper;
import com.cloudinary.Cloudinary;
import com.equilar.bsp.config.RedisConfig;
import com.equilar.bsp.config.SecurityConfig;
import com.equilar.bsp.mvc.MvcConfig;
import com.equilar.bsp.util.JwtTokenGenerator;
import com.equilar.bsp.util.Util;
#SpringBootApplication
#EnableScheduling
#Configuration
#EnableAutoConfiguration
#EnableJpaAuditing
//#ComponentScan(basePackages = "com.equilar" ,lazyInit = true)
#EnableJpaRepositories("com.equilar")
#EntityScan({"com.equilar.bsp.domain", "com.equilar.newcommon.folder.domain", "com.equilar.newcommon.pdf.domain"})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
// set default timezone first thing!!
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SpringApplication.run(Application.class, args);
JwtTokenGenerator.getStartTime();
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass, SecurityConfig.class, MvcConfig.class, RedisConfig.class);
}
private static Class<Application> applicationClass = Application.class;
#PreDestroy
private void cleanUp() {
/* try {
// Shutting down AWS IdleConnectionReaper thread...
IdleConnectionReaper.shutdown();
List<Thread> threadsList = getThreadByName("logback-loggly-appender");
if(!Util.isNullOrEmptyCollection(threadsList)){
for (Thread thread : threadsList) {
thread.interrupt();
}
}
} catch (Throwable t) {
// log error
t.printStackTrace();
}*/
}
/*public List<Thread> getThreadByName(String threadName) {
List<Thread> threads = new ArrayList<Thread>();
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(threadName)){
threads.add(t);
}
}
return threads;
}*/
#Value("${CLOUDINARY_URL}")
private String cloudinaryUrl;
#Bean(name = "cloudinary")
public Cloudinary Instance() {
return new Cloudinary(cloudinaryUrl);
}
}
package com.equilar.bsp.calc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
#org.springframework.stereotype.Component
public class Component {
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Scheduled(
cron = "0,30 * * * * *")
public void cronJob() {
logger.info("> cronJob");
logger.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>> In Chron Job."
);
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
}
}
Your code sample looks totally fine for me. Moreover, I've created a project with sample code you've provided and it worked( with spring.boot.version 1.2.1.RELEASE ).
There is a similar project on github you may be interested in.

How to make JHipster 'hot reload' classes

I'm using default generated jhipster application and I'm wondering how to make it 'hot reload' using spring-boot-devtools.
That's how I tried to start this application in 2 different ways:
http://prntscr.com/a4dhmu or http://prntscr.com/a4di2c
spring-boot-devtools library is included in dev profile (just simple generated pom.xml) and my Application.class is default:
package com.testnewfeatures.app;
import com.testnewfeatures.app.config.Constants;
import com.testnewfeatures.app.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
#ComponentScan
#EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, HazelcastAutoConfiguration.class })
#EnableConfigurationProperties({ JHipsterProperties.class, LiquibaseProperties.class })
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
#Inject
private Environment env;
/**
* Initializes TestNewFeatures.
* <p/>
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
* <p/>
* <p>
* You can find more information on how profiles work with JHipster on http://jhipster.github.io/profiles.html.
* </p>
*/
#PostConstruct
public void initApplication() throws IOException {
if (env.getActiveProfiles().length == 0) {
log.warn("No Spring profile configured, running with default configuration");
} else {
log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! " +
"It should not run with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION) && activeProfiles.contains(Constants.SPRING_PROFILE_FAST)) {
log.error("You have misconfigured your application! " +
"It should not run with both the 'prod' and 'fast' profiles at the same time.");
}
if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! " +
"It should not run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
}
/**
* Main method, used to run the application.
*/
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(Application.class);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
addDefaultProfile(app, source);
Environment env = app.run(args).getEnvironment();
log.info("Access URLs:\n----------------------------------------------------------\n\t" +
"Local: \t\thttp://127.0.0.1:{}\n\t" +
"External: \thttp://{}:{}\n----------------------------------------------------------",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"));
}
/**
* If no profile has been configured, set by default the "dev" profile.
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active") &&
!System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
}
I'm doing something wrong becaus 'Hot reload' doesn't appear when I change any class.
Thanks!
Also according to your screenshots you use IDEA which does not auto compile classes on save by default, have you tried trigerring a build manually or the tricks below?
Intellij IDEA Java classes not auto compiling on save

Categories