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
Related
I am using Spring Boot 3.0.0 , Spring Cloud 2021.0.5 . I have BillingServiceApplication.java
package org.sid.billingservice;
import org.sid.billingservice.entities.Bill;
import org.sid.billingservice.entities.ProductItem;
import org.sid.billingservice.model.Customer;
import org.sid.billingservice.model.Product;
import org.sid.billingservice.repository.BillRepository;
import org.sid.billingservice.repository.ProductItemRepository;
import org.sid.billingservice.services.CustomerRestClient;
import org.sid.billingservice.services.ProductRestClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import java.util.Collection;
import java.util.Date;
import java.util.Random;
#SpringBootApplication
#EnableFeignClients
#ImportAutoConfiguration({FeignAutoConfiguration.class})
public class BillingServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BillingServiceApplication.class, args);
}
#Bean
CommandLineRunner start(BillRepository billRepository, ProductItemRepository productItemRepository, CustomerRestClient customerRestClient, ProductRestClient productRestClient) {
return args -> {
Collection<Product> products = productRestClient.allProducts().getContent();
Long customerId = 1L;
Customer customer = customerRestClient.findCustomerById(customerId);
if (customer == null) throw new RuntimeException("Customer not found");
Bill bill = new Bill();
bill.setBillDate(new Date());
bill.setCustomerId(customerId);
Bill savedBill = billRepository.save(bill);
products.forEach(product -> {
ProductItem productItem = new ProductItem();
productItem.setBill(savedBill);
productItem.setProductId(product.getId());
productItem.setQuantity(1 + new Random().nextInt(10));
productItem.setPrice(product.getPrice());
productItem.setDiscount(Math.random());
productItemRepository.save(productItem);
});
};
}
}
my error
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?
Log error full https://gist.github.com/donhuvy/348aa7b096cde63a7129ad0f009c7507
How to fix it?
please share your pom.xml. It looks like you don't have spring-cloud-starter-loadbalancer dependency in your project.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>2.4.4</version>
</dependency>
Replacing path with url in feign client class along with #ImportAutoConfiguration({FeignAutoConfiguration.class}) in main class worked for me.
Camunda normally uses UUIDs (e. g. 98631715-0b07-11ec-ab3b-68545a6e5055) as process instance IDs. In my project a process instance ID like 124 is being generated which looks suspicious to me.
This behavior can be reproduced as described below.
Step 1
Check out this repository and start the process engines
core-processes,
core-workflow and
domain-hello-world
so that all of them use the same shared database.
Step 2
Login to the Camunda UI at http://localhost:8080 and navigate to the tasklist.
Start the Starter process in tasklist.
Step 3
Go to the cockpit and navigate to Running process instances (http://localhost:8080/camunda/app/cockpit/default/#/processes).
Click on DomainProcess.
In column ID you will see a numeric (135 in the screenshot above) process instance ID, not a UUID.
Probable cause of the error
In core-processs engine I have the following Config class:
import org.camunda.bpm.engine.impl.history.HistoryLevel;
import org.camunda.bpm.engine.impl.history.event.HistoryEvent;
import org.camunda.bpm.engine.impl.history.handler.CompositeHistoryEventHandler;
import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler;
import org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import static org.apache.commons.lang3.ArrayUtils.addAll;
#Configuration
public class Config {
private static final Logger LOGGER = LoggerFactory.getLogger(Config.class);
#Autowired
#Qualifier("camundaBpmDataSource")
private DataSource dataSource;
#Autowired
#Qualifier("camundaTxManager")
private PlatformTransactionManager txManager;
#Autowired
private ResourcePatternResolver resourceLoader;
#Bean
public SpringProcessEngineConfiguration processEngineConfiguration() {
final SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
config.setDataSource(dataSource);
config.setTransactionManager(txManager);
config.setDatabaseSchemaUpdate("true");
config.setHistory(HistoryLevel.HISTORY_LEVEL_FULL.getName());
config.setJobExecutorActivate(true);
config.setMetricsEnabled(false);
final Logger logger = LoggerFactory.getLogger("History Event Handler");
final HistoryEventHandler testHistoryEventHandler = new HistoryEventHandler() {
#Override
public void handleEvent(final HistoryEvent evt) {
LOGGER.debug("handleEvent | " + evt.getProcessInstanceId() + " | "
+ evt.toString());
}
#Override
public void handleEvents(final List<HistoryEvent> events) {
for (final HistoryEvent curEvent : events) {
handleEvent(curEvent);
}
}
};
config.setHistoryEventHandler(new CompositeHistoryEventHandler(Collections.singletonList(testHistoryEventHandler)));
try {
final Resource[] bpmnResources = resourceLoader.getResources("classpath:*.bpmn");
final Resource[] dmnResources = resourceLoader.getResources("classpath:*.dmn");
config.setDeploymentResources(addAll(bpmnResources, dmnResources));
} catch (final IOException exception) {
exception.printStackTrace();
LOGGER.error("An error occurred while trying to deploy BPMN and DMN files", exception);
}
return config;
}
}
If I remove this configuration (or comment the #Configuration line), the error disappears.
Questions
Why does Camunda generate a numeric process instance ID in this case (and not a UUID as in other cases)?
After adding the line
config.setIdGenerator(new StrongUuidGenerator());
in the configuration class
#Bean
public SpringProcessEngineConfiguration processEngineConfiguration() {
final SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
config.setIdGenerator(new StrongUuidGenerator());
config.setDataSource(dataSource);
the process instance IDs became UUIDs again.
For details see Camunda documentation on ID generators.
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);
}
}
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.
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.