Why can't I log before starting a Spring Boot Application? - spring

I am trying to log something before my Spring Boot application starts. Here is a snippet below. I am using Lombok and Log4J2 and I have done the spring-boot-starter-logging exclusion + added spring-boot-starter-log4j2. I was wondering how to make it work and why the present code does not work.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.extern.log4j.Log4j2;
#SpringBootApplication
#Log4j2
public class DemoApplication {
public static void main(String[] args) {
log.info("Does not work");
SpringApplication.run(DemoApplication.class, args);
log.info("Works");
}
}
Result in console:
2020-11-30 19:45:32.667 INFO 25132 --- [ main] c.e.d.DemoApplication : Starting DemoApplication using Java 11.0.1 on *** with PID 25132 (**** started by **** in ****)
2020-11-30 19:45:32.702 INFO 25132 --- [ main] c.e.d.DemoApplication : No active profile set, falling back to default profiles: default
2020-11-30 19:45:33.921 INFO 25132 --- [ main] c.e.d.DemoApplication : Started DemoApplication in 2.008 seconds (JVM running for 3.103)
2020-11-30 19:45:33.927 INFO 25132 --- [ main] c.e.d.DemoApplication : Works
Updated:
However, as shown below, using Slf4j with default LogBack works, why not Log4j2?
(Log4j2 with Slf4j still does not)
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.extern.slf4j.Slf4j;
#Slf4j
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
log.info("Does not work");
SpringApplication.run(DemoApplication.class, args);
log.info("Works");
}
}
20:04:25.945 [main] INFO com.example.demo.DemoApplication - Does not work
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.0)
2020-11-30 20:04:26.463 INFO 33284 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 11.0.1 on **** with PID 33284 (**** started by **** in ****)
2020-11-30 20:04:26.465 INFO 33284 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2020-11-30 20:04:27.234 INFO 33284 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.17 seconds (JVM running for 2.109)
2020-11-30 20:04:27.242 INFO 33284 --- [ main] com.example.demo.DemoApplication : Works

In the end I was able to answer my own question by stepping through the code + some research. Sharing my results:
In Log4j2, the default root filter level, when not providing a config (or before Spring instantiates the Log4j2-spring config) is ERROR, therefore isEnabled returns false and the logger does not print to the console the first time. However, once instantiated by Spring, the level becomes INFO and therefore the messages is printed to the console as the log level is now superior or equal to INFO level. QED

Related

There's a ghost code in the boot spring What's the problem?

I'm Java Boots Spring, Maven
In the spring,
We added jpa and Thymereaf as dependencies.
And I ran.
However, the working http://localhost:8080/ was disconnected and an error occurred.
The same was true of other dependencies added.
So I deleted it again from pom.xml.
However, the local host did not work again.
And I found something strange in the class I added.
I annotated it, but it didn't work.
The controller worked after deleting the class code.
Even if I deleted the class, the controller worked.
This is a ghost code.
And this is an added class.
/*
package com.team2.crowdfunding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class MemberController {
#GetMapping("/save")
public String saveForm() {
return "/user/save";
}
#GetMapping("/")
public String saveForm2() {
System.out.println("겟 처음");
return "/index";
}
}
*/
And this is the spring that outputs.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.5)
2022-11-29 16:01:17.947 INFO 19648 --- [ restartedMain] c.t.c.CrowdfundingApplication : Starting CrowdfundingApplication using Java 18.0.2.1 on DESKTOP-TMFMLDT with PID 19648 (C:\Users\bitcamp\IdeaProjects\crowdfunding2\target\classes started by bitcamp in C:\Users\bitcamp\IdeaProjects\crowdfunding2)
2022-11-29 16:01:17.948 INFO 19648 --- [ restartedMain] c.t.c.CrowdfundingApplication : No active profile set, falling back to 1 default profile: "default"
2022-11-29 16:01:17.988 INFO 19648 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-11-29 16:01:17.988 INFO 19648 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-11-29 16:01:18.463 WARN 19648 --- [ restartedMain] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[com.team2.crowdfunding]' package. Please check your configuration.
2022-11-29 16:01:18.812 INFO 19648 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-11-29 16:01:18.821 INFO 19648 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-11-29 16:01:18.821 INFO 19648 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68]
2022-11-29 16:01:18.994 INFO 19648 --- [ restartedMain] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2022-11-29 16:01:18.998 INFO 19648 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-11-29 16:01:18.999 INFO 19648 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1010 ms
2022-11-29 16:01:19.203 INFO 19648 --- [ restartedMain] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation should only be used on methods with parameters: public org.springframework.security.crypto.password.PasswordEncoder com.team2.crowdfunding.controller.UserController.passwordEncoder()
2022-11-29 16:01:19.322 INFO 19648 --- [ restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: ServletContext resource [/index.html]
2022-11-29 16:01:19.452 INFO 19648 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-11-29 16:01:19.483 INFO 19648 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-11-29 16:01:19.491 INFO 19648 --- [ restartedMain] c.t.c.CrowdfundingApplication : Started CrowdfundingApplication in 1.81 seconds (JVM running for 2.124)
2022-11-29 16:01:22.123 INFO 19648 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-11-29 16:01:22.123 INFO 19648 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-11-29 16:01:22.124 INFO 19648 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
What's the problem?
........................

Print Hello World before Spring boot application start

Hello guys I want to ask if its possible to execute the print before the spring boot application start?
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SampleApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
#Override
public void run(String... args) {
System.out.print("I would be appear in log first before spring application starts");
}
}
My problem of my code it will display the print after the spring boot application start
Current Output
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.2)
2021-09-26 06:13:53.267 INFO 10352 --- [ main] c.s.d.SampleApplicationTests : Starting SampleApplicationTests using Java 11.0.11 on User-Desktop with PID 10352 (started by ???)
2021-09-26 06:13:53.277 INFO 10352 --- [ main] c.s.d.Sample
ApplicationTests : No active profile set, falling back to default profiles: default
2021-09-26 06:13:54.879 INFO 10352 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-09-26 06:13:55.051 INFO 10352 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 148 ms. Found 9 JPA repository interfaces.
2021-09-26 06:13:57.118 INFO 10352 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-09-26 06:13:57.299 INFO 10352 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-09-26 06:13:57.563 INFO 10352 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-09-26 06:13:58.268 INFO 10352 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-09-26 06:14:03.062 INFO 10352 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-09-26 06:14:03.094 INFO 10352 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
2021-09-26 06:14:08.430 INFO 10352 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-09-26 06:14:08.453 INFO 10352 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-09-26 06:14:15.216 INFO 10352 --- [ main] c.s.d.SampleApplicationTests : Started SampleApplicationTests in 22.607 seconds (JVM running for 24.991)
I would be appear in log first before spring application starts
Why don't you just print the log in main method before run invocation?
#SpringBootApplication
public class SampleApplication implements CommandLineRunner {
public static void main(String[] args) {
System.out.print("I would be appear in log first before spring application starts");
SpringApplication.run(SampleApplication.class, args);
}
#Override
public void run(String... args) {
}
}
run method is a method from Spring Boot so everything you do there is done after Spring Boot's start.
If by before the spring boot application start you mean application context startup, then yes, the easiest (for singletons beans, anyway) being to annotate your method with #PostConstruct.
#PostConstruct
public void init() {
//do something
}
Check for the #PostConstruct for e.g here.

JMS not starting in Spring Boot application

I developed a spring boot application which send and listen message in Activemq using JMS, but while running application, JMS is not getting started by spring boot
This is mainclass, Application.java
#SpringBootApplication
#EnableJms
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Configuration class: Config.java
#Configuration
public class Config {
#Bean
public Queue queue() {
return new ActiveMQQueue("inmemory.queue");
}
#Bean
public JmsTemplate jmsTemplate() {
return new JmsTemplate(activeMQConnectionFactory());
}
}
Listener class is used to listen to the queue: Listener.java
#Component
public class Listener {
#JmsListener(destination = "inmemory.queue")
public void listener(String message) {
System.out.println("message received" + message);
}
}
Producer class is used to send message to queue from controller: Producer.java
#RestController
public class Producer {
#Autowired
Queue queue;
#Autowired
JmsTemplate jmstemplate;
#RequestMapping(method = RequestMethod.GET, path = "/test3/{message}")
public String test3(#PathVariable String message) {
jmstemplate.convertAndSend(queue, message);
return "teste3" + message;
}
}
application.properties
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
server.port=8081
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-broker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>
This is a screenshot of application starting without starting JMS
Please use below code for jmsTemplate(...) method.
#Bean
public JmsTemplate jmsTemplate() {
return new JmsTemplate(new ActiveMQConnectionFactory("vm://localhost"));
}
I have tested and it is working, let me know if you need sample code.
Also, no need to install ActiveMQ in local when you are using a starter.
Output
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.6.RELEASE)
2019-09-16 12:39:15.477 INFO 14111 --- [ main] c.e.activeissue.ActiveIssueApplication : Starting ActiveIssueApplication on kode12-B250M-D3H with PID 14111 (/home/yprajapati/Downloads/active-issue/target/classes started by yprajapati in /home/yprajapati/Downloads/active-issue)
2019-09-16 12:39:15.493 INFO 14111 --- [ main] c.e.activeissue.ActiveIssueApplication : No active profile set, falling back to default profiles: default
2019-09-16 12:39:16.895 INFO 14111 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2019-09-16 12:39:16.919 INFO 14111 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-09-16 12:39:16.919 INFO 14111 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-09-16 12:39:16.991 INFO 14111 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-09-16 12:39:16.991 INFO 14111 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1407 ms
2019-09-16 12:39:17.204 INFO 14111 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-16 12:39:17.440 INFO 14111 --- [ main] o.apache.activemq.broker.BrokerService : Using Persistence Adapter: MemoryPersistenceAdapter
2019-09-16 12:39:17.505 INFO 14111 --- [ JMX connector] o.a.a.broker.jmx.ManagementContext : JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
2019-09-16 12:39:17.574 INFO 14111 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.15.9 (localhost, ID:kode12-B250M-D3H-39191-1568617757456-0:1) is starting
2019-09-16 12:39:17.577 INFO 14111 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.15.9 (localhost, ID:kode12-B250M-D3H-39191-1568617757456-0:1) started
2019-09-16 12:39:17.577 INFO 14111 --- [ main] o.apache.activemq.broker.BrokerService : For help or more information please see: http://activemq.apache.org
2019-09-16 12:39:17.594 INFO 14111 --- [ main] o.a.activemq.broker.TransportConnector : Connector vm://localhost started
2019-09-16 12:39:17.734 INFO 14111 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2019-09-16 12:39:17.737 INFO 14111 --- [ main] c.e.activeissue.ActiveIssueApplication : Started ActiveIssueApplication in 2.872 seconds (JVM running for 3.326)

Whitelabel error page on localhost:8080\sendMesssage?

I have just started Springboot with Twilio but for some reason when I run the localhost\sendMessage command I get the Whitelabel error Page. When I run the below code the test concludes successfully:
package com.example.demo
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping
#RestController
public class SMSController{
#RequestMapping( "/")
fun helloSpringBoot() = "Hello Spring Boot!"
}
This is the result of the code above:
But when I run the below code with the localhost:8080\sendMessage I get the screenshot that follows the code:
package com.example.demo
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping
import com.twilio.http.TwilioRestClient
import com.twilio.rest.api.v2010.account.MessageCreator
import com.twilio.type.PhoneNumber
#RestController
public class SMSController{
#RequestMapping("/sendMessage")
fun sendMessage(){
val client = TwilioRestClient.Builder(
System.getenv("ACCOUNT_SID"),
System.getenv("AUTH_TOKEN")).build()
val message = MessageCreator(
PhoneNumber(System.getenv("+1..........")),
PhoneNumber("+1.........."),
"Lambda is annoying..Sigh"
).create(client)
}
}
Am I missing something?
I have added my Stack TRace:
"C:\Program Files\Java\jdk1.8.0_25\bin\java.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1\lib\idea_rt.jar=25281:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_25\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\rt.jar;C:\Users\Jevon\IdeaProjects\demo\out\production\classes;C:\Users\Jevon\IdeaProjects\demo\out\production\resources;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.twilio.sdk\twilio\7.17.9\8de7649313c8fa3dfcbd215b6c0300ca1c4184f5\twilio-7.17.9.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-web\2.1.4.RELEASE\a4659d55f57421a5ef122cb670b7b544ef8190e8\spring-boot-starter-web-2.1.4.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-json\2.1.4.RELEASE\247d7c2efae986f310a29e9fef7174adc91d0835\spring-boot-starter-json-2.1.4.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter\2.1.4.RELEASE\8fa436ef4e273cb476d5dc3aa73701a8837460af\spring-boot-starter-2.1.4.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-reflect\1.3.21\d0d5ff2ac2ebd8a42697af41e20fc225a23c5d3b\kotlin-reflect-1.3.21.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-stdlib-jdk8\1.3.21\d0634d54452abc421db494ad32dd215e6591c49f\kotlin-stdlib-jdk8-1.3.21.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.google.guava\guava\18.0\cce0823396aa693798f8882e64213b1772032b09\guava-18.0.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\joda-time\joda-time\2.10.1\9ac3dbf89dbf2ee385185dd0cd3064fe789efee0\joda-time-2.10.1.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\io.jsonwebtoken\jjwt\0.4\61ce246d937a0fd3acf06d3bef5fc9e3933ae812\jjwt-0.4.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.apache.httpcomponents\httpclient\4.5.8\c27c9d6f15435dc2b6947112027b418b0eef32b9\httpclient-4.5.8.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.apache.httpcomponents\httpcore\4.4.11\de748cf874e4e193b42eceea9fe5574fabb9d4df\httpcore-4.4.11.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.datatype\jackson-datatype-jdk8\2.9.8\bcd02aa9195390e23747ed40bf76be869ad3a2fb\jackson-datatype-jdk8-2.9.8.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.datatype\jackson-datatype-jsr310\2.9.8\28ad1bced632ba338e51c825a652f6e11a8e6eac\jackson-datatype-jsr310-2.9.8.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.module\jackson-module-parameter-names\2.9.8\c4eef0e6e20d60fb27af4bc4770dba7bcc3f6de6\jackson-module-parameter-names-2.9.8.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-databind\2.9.8\11283f21cc480aa86c4df7a0a3243ec508372ed2\jackson-databind-2.9.8.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-core\2.9.8\f5a654e4675769c716e5b387830d19b501ca191\jackson-core-2.9.8.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-annotations\2.9.0\7c10d545325e3a6e72e06381afe469fd40eb701\jackson-annotations-2.9.0.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\javax.xml.bind\jaxb-api\2.3.1\8531ad5ac454cc2deb9d4d32c40c4d7451939b5d\jaxb-api-2.3.1.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-tomcat\2.1.4.RELEASE\3b0c04450d86fc29c9fdad555b4555e553a4008\spring-boot-starter-tomcat-2.1.4.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.hibernate.validator\hibernate-validator\6.0.16.Final\ad9557c558972093c0567a2a1f224f318c00f650\hibernate-validator-6.0.16.Final.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-webmvc\5.1.6.RELEASE\cf4ea53740c93e0b8ff951ef0a3eaf154c74dbd0\spring-webmvc-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-web\5.1.6.RELEASE\4e15a24feba0581a02efd508af03a15b05570bd4\spring-web-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-autoconfigure\2.1.4.RELEASE\d5f8b3f7835a23b4dfd8d1489d265c1e426e317b\spring-boot-autoconfigure-2.1.4.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot\2.1.4.RELEASE\5ad0355a8c810b32b9221b9b92746b51c983337f\spring-boot-2.1.4.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-logging\2.1.4.RELEASE\2fb669a89cd65b275be20ab755c3742399395dff\spring-boot-starter-logging-2.1.4.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\javax.annotation\javax.annotation-api\1.3.2\934c04d3cfef185a8008e7bf34331b79730a9d43\javax.annotation-api-1.3.2.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-context\5.1.6.RELEASE\7b9e80ab68ee91ca0462a0eb2c58a9d957788b\spring-context-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-aop\5.1.6.RELEASE\a473d4bca7295f2b90522594e413f9e19107c1d2\spring-aop-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-beans\5.1.6.RELEASE\90d2f4bf7eced108de0b5bf617abb2b13a6206a3\spring-beans-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-expression\5.1.6.RELEASE\50fe4080029e43e7612e50fb4d7c7c43e95bf03c\spring-expression-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-core\5.1.6.RELEASE\9329591e728ef9844911e082e399f4fc3e3ecb37\spring-core-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-stdlib-jdk7\1.3.21\d207ce2c9bcf17dc8e51bab4dbfdac4d013e7138\kotlin-stdlib-jdk7-1.3.21.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-stdlib\1.3.21\4bcc2012b84840e19e1e28074284cac908be0295\kotlin-stdlib-1.3.21.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\ch.qos.logback\logback-classic\1.2.3\7c4f3c474fb2c041d8028740440937705ebb473a\logback-classic-1.2.3.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.apache.logging.log4j\log4j-to-slf4j\2.11.2\6d37bf7b046c0ce2669f26b99365a2cfa45c4c18\log4j-to-slf4j-2.11.2.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.yaml\snakeyaml\1.23\ec62d74fe50689c28c0ff5b35d3aebcaa8b5be68\snakeyaml-1.23.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.slf4j\jul-to-slf4j\1.7.26\8031352b2bb0a49e67818bf04c027aa92e645d5c\jul-to-slf4j-1.7.26.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.slf4j\slf4j-api\1.7.26\77100a62c2e6f04b53977b9f541044d7d722693d\slf4j-api-1.7.26.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\commons-codec\commons-codec\1.11\3acb4705652e16236558f0f4f2192cc33c3bd189\commons-codec-1.11.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\javax.activation\javax.activation-api\1.2.0\85262acf3ca9816f9537ca47d5adeabaead7cb16\javax.activation-api-1.2.0.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.apache.tomcat.embed\tomcat-embed-websocket\9.0.17\a786505cc2697f7f2d8693c0c318270cc8addd92\tomcat-embed-websocket-9.0.17.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.apache.tomcat.embed\tomcat-embed-core\9.0.17\aacb92c34eb2e88f38a060c9fcaaae329a79c9ca\tomcat-embed-core-9.0.17.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.apache.tomcat.embed\tomcat-embed-el\9.0.17\595fbb87426e23f27c71b267f22b6e7d2a91a2aa\tomcat-embed-el-9.0.17.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\javax.validation\validation-api\2.0.1.Final\cb855558e6271b1b32e716d24cb85c7f583ce09e\validation-api-2.0.1.Final.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.jboss.logging\jboss-logging\3.3.2.Final\3789d00e859632e6c6206adc0c71625559e6e3b0\jboss-logging-3.3.2.Final.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\com.fasterxml\classmate\1.4.0\291658ac2ce2476256c7115943652c0accb5c857\classmate-1.4.0.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.springframework\spring-jcl\5.1.6.RELEASE\a4ad3c98c7cc31357e94e12772c8e6449522bc5\spring-jcl-5.1.6.RELEASE.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-stdlib-common\1.3.21\f30e4a9897913e53d778f564110bafa1fef46643\kotlin-stdlib-common-1.3.21.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.jetbrains\annotations\13.0\919f0dfe192fb4e063e7dacadee7f8bb9a2672a9\annotations-13.0.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\ch.qos.logback\logback-core\1.2.3\864344400c3d4d92dfeb0a305dc87d953677c03c\logback-core-1.2.3.jar;C:\Users\Jevon\.gradle\caches\modules-2\files-2.1\org.apache.logging.log4j\log4j-api\2.11.2\f5e9a2ffca496057d6891a3de65128efc636e26e\log4j-api-2.11.2.jar" com.example.demo.DemoApplicationKt
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.4.RELEASE)
2019-04-04 15:32:35.584 INFO 8012 --- [ main] com.example.demo.DemoApplicationKt : Starting DemoApplicationKt on Javy26 with PID 8012 (C:\Users\Jevon\IdeaProjects\demo\out\production\classes started by Jevon in C:\Users\Jevon\IdeaProjects\demo)
2019-04-04 15:32:35.596 INFO 8012 --- [ main] com.example.demo.DemoApplicationKt : No active profile set, falling back to default profiles: default
2019-04-04 15:32:35.828 WARN 8012 --- [kground-preinit] o.s.h.c.j.Jackson2ObjectMapperBuilder : For Jackson Kotlin classes support please add "com.fasterxml.jackson.module:jackson-module-kotlin" to the classpath
2019-04-04 15:32:39.918 INFO 8012 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-04-04 15:32:39.970 INFO 8012 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-04-04 15:32:39.970 INFO 8012 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-04 15:32:40.214 INFO 8012 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-04-04 15:32:40.214 INFO 8012 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4486 ms
2019-04-04 15:32:41.275 INFO 8012 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-04 15:32:41.807 INFO 8012 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-04 15:32:41.811 INFO 8012 --- [ main] com.example.demo.DemoApplicationKt : Started DemoApplicationKt in 7.81 seconds (JVM running for 10.279)
2019-04-04 15:33:24.230 INFO 8012 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-04-04 15:33:24.230 INFO 8012 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-04-04 15:33:24.250 INFO 8012 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 20 ms
I went back through the Kotlin documentation rather than focus on the tutorial and made the necessary changes. Once that was done the code started working as it should. See changes below:
#RestController
public class SMSController{
#RequestMapping(value = ["/sendMessage"])
fun sendMessage(){
val client = TwilioRestClient.Builder("ACCOUNT_SID",
"AUTH_TOKEN").build()
val message = MessageCreator(
PhoneNumber("+1........"),
PhoneNumber("+1........"),
"Lambda is annoying..Sigh").create(client)
}
}

Spring Cloud Task deployed on PCF fails to exit on TaskExecution end

I am trying to host a Spring cloud task app on PCF and run the task hourly using PCF scheduler's CRON jobs. However, as part of the task, I have to publish a message onto a RabbitMQ exchange. The RabbitMQ instance is a RabbitMQ on PCF service which is bound to the task app. When I run the task, the Task Execution ends but the application does not shut down, thereby causing the task instance to be permanently in the running state.
This is the code for my application class.
package com.example.demo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.task.configuration.EnableTask;
#EnableTask
#SpringBootApplication
public class DemoApplication implements CommandLineRunner {
final String topicExchangeName = "demo-exchange";
#Autowired
RabbitTemplate rabbitTemplate;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args).close();
}
#Override
public void run(String... args) throws Exception {
System.out.println("Hello Task Demo!");
rabbitTemplate.convertAndSend(topicExchangeName, "HLT", "Hello Task!");
}
}
This is the application.properties file
logging.level.org.springframework.cloud.task=DEBUG
spring.application.name=helloTaskApp
spring.cloud.task.closecontext_enable=true
spring.cloud.task.events.enabled=false
The following is the logs for a task run
2019-02-11T17:20:47.468+05:30 [APP/TASK/sample-task/0] [OUT] :: Spring Boot :: (v2.1.2.RELEASE)
2019-02-11T17:20:47.468+05:30 [APP/TASK/sample-task/0] [OUT] =========|_|==============|___/=/_/_/_/
2019-02-11T17:20:47.468+05:30 [APP/TASK/sample-task/0] [OUT] ' |____| .__|_| |_|_| |_\__, | / / / /
2019-02-11T17:20:47.468+05:30 [APP/TASK/sample-task/0] [OUT] \\/ ___)| |_)| | | | | || (_| | ) ) ) )
2019-02-11T17:20:47.468+05:30 [APP/TASK/sample-task/0] [OUT] ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
2019-02-11T17:20:47.468+05:30 [APP/TASK/sample-task/0] [OUT] /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
2019-02-11T17:20:47.468+05:30 [APP/TASK/sample-task/0] [OUT] . ____ _ __ _ _
2019-02-11T17:20:47.652+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:47.649 INFO 10 --- [ main] pertySourceApplicationContextInitializer : 'cloud' property source added
2019-02-11T17:20:47.653+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:47.653 INFO 10 --- [ main] nfigurationApplicationContextInitializer : Reconfiguration enabled
2019-02-11T17:20:47.661+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:47.661 INFO 10 --- [ main] com.example.demo.DemoApplication : The following profiles are active: cloud
2019-02-11T17:20:47.661+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:47.660 INFO 10 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on 91defac2-7964-41f1-8b39-096c9e32ca32 with PID 10 (/home/vcap/app/BOOT-INF/classes started by vcap in /home/vcap/app)
2019-02-11T17:20:48.304+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:48.303 INFO 10 --- [ main] o.c.reconfiguration.CloudServiceUtils : 'rabbitConnectionFactory' bean of type with 'org.springframework.amqp.rabbit.connection.ConnectionFactory' reconfigured with 'rabbit-1' bean
2019-02-11T17:20:48.327+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:48.327 INFO 10 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.amqp.rabbit.annotation.RabbitBootstrapConfiguration' of type [org.springframework.amqp.rabbit.annotation.RabbitBootstrapConfiguration$$EnhancerBySpringCGLIB$$ec22c458] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-02-11T17:20:48.505+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:48.505 DEBUG 10 --- [ main] o.s.c.t.c.DefaultTaskConfigurer : No DataSource was found, using ResourcelessTransactionManager
2019-02-11T17:20:48.505+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:48.505 DEBUG 10 --- [ main] o.s.c.t.c.SimpleTaskAutoConfiguration : Using org.springframework.cloud.task.configuration.DefaultTaskConfigurer TaskConfigurer
2019-02-11T17:20:48.864+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:48.863 DEBUG 10 --- [ main] o.s.c.t.r.support.SimpleTaskRepository : Creating: TaskExecution{executionId=0, parentExecutionId=null, exitCode=null, taskName='helloTaskApp', startTime=Mon Feb 11 11:50:48 UTC 2019, endTime=null, exitMessage='null', externalExecutionId='null', errorMessage='null', arguments=[]}
2019-02-11T17:20:48.872+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:48.872 INFO 10 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.742 seconds (JVM running for 2.43)
2019-02-11T17:20:48.873+05:30 [APP/TASK/sample-task/0] [OUT] Hello Task Demo!
2019-02-11T17:20:48.876+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:48.876 INFO 10 --- [ main] o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [*****]
2019-02-11T17:20:49.017+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:49.016 INFO 10 --- [ main] o.s.a.r.c.CachingConnectionFactory : Created new connection: SpringAMQP#fdefd3f:0/SimpleConnection#527e5409 [delegate=amqp://8de6f119-e720-4baf-b2f7-cf8d7704985e#10.32.27.77:5672/ac4af8cd-c6ff-4da2-a645-b14f27eea150, localPort= 55422]
2019-02-11T17:20:49.051+05:30 [APP/TASK/sample-task/0] [OUT] 2019-02-11 11:50:49.051 DEBUG 10 --- [ main] o.s.c.t.r.support.SimpleTaskRepository : Updating: TaskExecution with executionId=0 with the following {exitCode=0, endTime=Mon Feb 11 11:50:49 UTC 2019, exitMessage='null', errorMessage='null'}
I am using the command ".java-buildpack/open_jdk_jre/bin/java org.springframework.boot.loader.JarLauncher" for the task run.
It is running fine on local, but adding the RabbitTemplate seems to fail Application Context closing somehow. Can anyone help me understand why this is happening?
Not sure if this is a problem still but we ran into this after taking a spring upgrade to one of our tasks. The root cause of your / our issue seems to stem from this change. I guess the related issue for this is 462.
With that in mind you were close to a solution except for the property needed to be like this
spring.cloud.task.closecontextEnabled=true
The class that you can refer to is TaskProperties
This stemmed to the 'cloud' profile being added by the buildpack on PCF. You can see the same thing in my logs as well in the question.
Adding this environment variable on the manifest.yml
env:
JBP_CONFIG_SPRING_AUTO_RECONFIGURATION: '{enabled: false}'
This prevented the buildpack from loading the cloud autoconfiguration jars and application stopped after task run. In hindsight, more of a cloudfoundry buildpack issue rather than a spring cloud task one.

Resources