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.
Related
I have a very simple Spring Boot project with Spring Batch 5.0 and a CommmandLineRunner. There is one Job, one step, and one tasklet that simply prints "Running".
I followed directions and would expect the job to start and complete.
No errors; the Batch database table are being created; the Job and Step beans are being created.
It just doesn't run.
I would be grateful for any insights or assistance!
NOTE: If I launch the job explicitly from the CommandLineRunner using an autowired JobLauncher, it works fine. It just doesn't launch the job automatically (as promised).
NOTE 2: Removing #EnableBatchProcessing makes no difference.
Code follows
application.properties:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost/postgres
spring.batch.jdbc.initialize-schema=always
spring.batch.job.enabled=true
Application.java:
#SpringBootApplication
#EnableBatchProcessing
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Starting...");
Thread.sleep(2000);
}
}
Job configuration:
#Configuration
public class AbacusJobConfiguration {
Logger logger = LoggerFactory.getLogger(AbacusJobConfiguration.class);
#Bean
public Step step(JobRepository jobRepository, PlatformTransactionManager transactionManager, Tasklet tasklet1) {
logger.info("Building step");
return new StepBuilder("myTasklet", jobRepository)
.tasklet(tasklet1, transactionManager).allowStartIfComplete(true)
.build();
}
#Bean
public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager, Step step1) {
return new JobBuilder("myJob", jobRepository)
.incrementer(new RunIdIncrementer())
.start(step1)
.build();
}
#Bean
public MyTasklet myTasklet() {
logger.info("Building tasklet");
var tasklet = new MyTasklet();
return tasklet;
}
}
Tasklet:
public class MyTasklet implements Tasklet {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("Running MyTasklet");
return RepeatStatus.FINISHED;
}
}
Runtime log:
2023-01-30T10:54:07.407-05:00 INFO 72774 --- [ main] c.optionmetrics.abacuscli.Application : Starting Application using Java 17.0.6 with PID 72774 (/Users/dhait/IdeaProjects/abacus-cli/target/classes started by dhait in /Users/dhait/IdeaProjects/abacus-cli)
2023-01-30T10:54:07.410-05:00 INFO 72774 --- [ main] c.optionmetrics.abacuscli.Application : No active profile set, falling back to 1 default profile: "default"
2023-01-30T10:54:07.626-05:00 INFO 72774 --- [ main] o.s.b.c.c.annotation.BatchRegistrar : Finished Spring Batch infrastructure beans configuration in 2 ms.
2023-01-30T10:54:07.836-05:00 INFO 72774 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-01-30T10:54:07.918-05:00 INFO 72774 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection#6ae7deac
2023-01-30T10:54:07.919-05:00 INFO 72774 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-01-30T10:54:07.928-05:00 INFO 72774 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: POSTGRES
2023-01-30T10:54:07.940-05:00 INFO 72774 --- [ main] c.o.abacuscli.AbacusJobConfiguration : Building tasklet
2023-01-30T10:54:07.942-05:00 INFO 72774 --- [ main] c.o.abacuscli.AbacusJobConfiguration : Building step
2023-01-30T10:54:07.954-05:00 INFO 72774 --- [ main] .c.a.BatchObservabilityBeanPostProcessor : No Micrometer observation registry found, defaulting to ObservationRegistry.NOOP
2023-01-30T10:54:07.959-05:00 INFO 72774 --- [ main] .c.a.BatchObservabilityBeanPostProcessor : No Micrometer observation registry found, defaulting to ObservationRegistry.NOOP
2023-01-30T10:54:07.963-05:00 INFO 72774 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2023-01-30T10:54:08.040-05:00 INFO 72774 --- [ main] c.optionmetrics.abacuscli.Application : Started Application in 0.882 seconds (process running for 1.246)
Starting...
2023-01-30T10:54:10.050-05:00 INFO 72774 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-01-30T10:54:10.054-05:00 INFO 72774 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
With Spring Boot 3, there is no need for #EnableBatchProcessing. If you add it, the auto-configuration of Spring Batch (including the automatic launching of jobs at startup) will back off.
This is mentioned in the migration guide of Spring Boot 3.
EDIT: Not able to reproduce the issue. Things are working as expected with Spring Batch 5 and Spring Boot 3.
$>curl https://start.spring.io/starter.zip -d dependencies=h2,batch -d type=maven-project -o my-batch-job.zip
$>unzip my-batch-job.zip
$> # Paste AbacusJobConfiguration and MyTasklet code in the demo package + add imports
$>./mvnw package
$>./mvnw spring-boot:run
This prints:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.2)
2023-01-31T07:48:24.206+01:00 INFO 91983 --- [ main] com.example.demo.DemoApplicationTests : Starting DemoApplicationTests using Java 17.0.4 with PID 91983 (started by mbenhassine in /Users/mbenhassine/Downloads/so75287102)
2023-01-31T07:48:24.207+01:00 INFO 91983 --- [ main] com.example.demo.DemoApplicationTests : No active profile set, falling back to 1 default profile: "default"
2023-01-31T07:48:24.625+01:00 INFO 91983 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-01-31T07:48:24.779+01:00 INFO 91983 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:0b237f7c-fec8-446f-b2ac-086801ddb7fd user=SA
2023-01-31T07:48:24.780+01:00 INFO 91983 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-01-31T07:48:24.858+01:00 INFO 91983 --- [ main] c.example.demo.AbacusJobConfiguration : Building tasklet
2023-01-31T07:48:24.860+01:00 INFO 91983 --- [ main] c.example.demo.AbacusJobConfiguration : Building step
2023-01-31T07:48:24.957+01:00 INFO 91983 --- [ main] com.example.demo.DemoApplicationTests : Started DemoApplicationTests in 0.91 seconds (process running for 1.585)
2023-01-31T07:48:24.958+01:00 INFO 91983 --- [ main] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
2023-01-31T07:48:24.990+01:00 INFO 91983 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=myJob]] launched with the following parameters: [{'run.id':'{value=1, type=class java.lang.Long, identifying=true}'}]
2023-01-31T07:48:25.009+01:00 INFO 91983 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [myTasklet]
Running MyTasklet
2023-01-31T07:48:25.017+01:00 INFO 91983 --- [ main] o.s.batch.core.step.AbstractStep : Step: [myTasklet] executed in 8ms
2023-01-31T07:48:25.025+01:00 INFO 91983 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=myJob]] completed with the following parameters: [{'run.id':'{value=1, type=class java.lang.Long, identifying=true}'}] and the following status: [COMPLETED] in 23ms
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.556 s - in com.example.demo.DemoApplicationTests
2023-01-31T07:48:25.312+01:00 INFO 91983 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-01-31T07:48:25.315+01:00 INFO 91983 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
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?
........................
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
The below line complaining bean not found.
private CustomUserDetailsService userDetailsService;
I think I've done what I need to do. I add #ComponentScan annotation to the bean and still not working.
Any idea and explanation ? Thanks a lot
SecurityConfiguration.java
// For pre-auth
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
#EnableJpaRepositories(basePackageClasses = UsersRepository.class)
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private CustomUserDetailsService userDetailsService;
......
}
CustomUserDetailsService.java
#ComponentScan
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UsersRepository usersRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Users> optionalUsers = usersRepository.findByName(username);
optionalUsers
.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
return optionalUsers
.map(CustomUserDetails::new).get();
}
}
UsersRepository.java
public interface UsersRepository extends JpaRepository<Users, Integer> {
Optional<Users> findByName(String username);
}
Log
17:00:01: Executing task 'bootRun'...
> Task :compileJava
> Task :processResources UP-TO-DATE
> Task :classes
> Task :bootRun
2019-10-13 17:00:03.588 ERROR 69399 --- [ main] o.s.b.c.l.LoggingApplicationListener : Cannot set level 'true' for 'org.hibernate.format_sql'
2019-10-13 17:00:03.591 ERROR 69399 --- [ main] o.s.b.c.l.LoggingApplicationListener : Cannot set level 'true' for 'org.hibernate.use_sql_comments'
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.9.RELEASE)
2019-10-13 17:00:03.690 INFO 69399 --- [ main] dev.house.xproj.XprojApplication : Starting XprojApplication on missions-mbp.lan with PID 69399 (/Users/poc/ workspace/15house-java-backend/build/classes/java/main started by poc in /Users/poc/workspace/15house-java-backend)
2019-10-13 17:00:03.691 INFO 69399 --- [ main] dev.house.xproj.XprojApplication : No active profile set, falling back to default profiles: default
2019-10-13 17:00:04.272 INFO 69399 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-10-13 17:00:04.295 INFO 69399 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 12ms. Found 0 repository interfaces.
2019-10-13 17:00:04.621 INFO 69399 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3e3b00fc] is not eligible for getting processed by all BeanPostProcessors ( for example: not eligible for auto-proxying)
2019-10-13 17:00:04.884 INFO 69399 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8083 (http)
2019-10-13 17:00:04.910 INFO 69399 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-10-13 17:00:04.910 INFO 69399 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.26]
2019-10-13 17:00:05.021 INFO 69399 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-10-13 17:00:05.021 INFO 69399 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1292 ms
2019-10-13 17:00:05.174 INFO 69399 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-10-13 17:00:05.599 INFO 69399 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-10-13 17:00:05.660 INFO 69399 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-10-13 17:00:05.738 INFO 69399 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.12.Final}
2019-10-13 17:00:05.739 INFO 69399 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-10-13 17:00:05.913 INFO 69399 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-10-13 17:00:06.059 INFO 69399 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-10-13 17:00:06.332 INFO 69399 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-10-13 17:00:06.552 INFO 69399 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-13 17:00:06.598 WARN 69399 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-10-13 17:00:06.867 INFO 69399 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: b3f078a7-2394-4323-96b0-1e54fc210699
2019-10-13 17:00:06.985 INFO 69399 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#31da0434, org.springframework.security.web.context.SecurityContextPersistenceFilter#14b31e37, org.springframework.security.web.header.HeaderWriterFilter#7fd4e815, org.springframework.security.web.csrf.CsrfFilter#3b78c683, org.springframework.security.web.authentication.logout.LogoutFilter#11c78080, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#62c3f556, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#3086f480, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#6e24ce51, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#60dc1a4e, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#5c48b72c, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#48cb2d73, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#423ed3b5, org.springframework.security.web.session.SessionManagementFilter#20cdb152, org.springframework.security.web.access.ExceptionTranslationFilter#2eda2062, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#72557746]
2019-10-13 17:00:07.077 INFO 69399 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8083 (http) with context path ''
2019-10-13 17:00:07.080 INFO 69399 --- [ main] dev.house.xproj.XprojApplication : Started XprojApplication in 3.756 seconds (JVM running for 4.113)
Might be u have missed, Include #Entity in User bean.
look here https://www.baeldung.com/jpa-entities
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)