Multiple SpringBoot apps, want to run only one - java

I'm currently working with SpringBootApplications, I have two differets #SpringBootApplication , one for Web Application, and a CommandLineRunner .
The problem is, no matter which of them I execute, it tries to run both of the applications.
package com.ws;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
#EnableAutoConfiguration
public class Init extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Init.class);
}
/**
* Main method.
*
* #param args String[].
* #throws Exception Exception.
*/
public static void main(String[] args) throws Exception {
SpringApplication.run(Init.class, args);
}
And this is my other InitBatch.java :
package com.batch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class InitBatch implements CommandLineRunner {
#Autowired
private Batch batch;
#Override
public void run(String... args) throws Exception {
batch.processFiles();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(InitBatch.class, args);
}
}
If I run the CommandLineRunner app, after it is executed, continues to load the Web App.
I need to be able to run each of them separately from each one. But I don't know how to configure this.
Thanks!

the spring docs say:
SpringBootApplication: This is a convenience annotation that is equivalent to declaring #Configuration, #EnableAutoConfiguration and #ComponentScan.
You should only ever add one #EnableAutoConfiguration annotation. We generally recommend that you add it to your primary #Configuration class.
so effectively you're adding 2 EnableAutoConfiguration annotations which just isn't allowed by spring boot. I would suggest using spring Profiles to achieve what you need.

Related

Field <repo_interface> in com.<package_name>.<service_class required a bean of type com.<package>.<repository>that could not be found

I'm new in spring-boot, and have spring-boot desktop test project with weird names, based on another example. The error given is:
`***************************
APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in com.test_4.test4.NonWebService required a bean of type 'com.test_4.test4.RandomTableREPO' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.test_4.test4.RandomTableREPO' in your configuration.`
And here are my classes:
**Test4Application**
package com.test_4.test4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Test4Application implements ExecuteI {
#Autowired
private NonWebService service;
public static void main(String[] args) {
SpringApplication.run(Test4Application.class, new String[]{"one_arg", "sec_arg"});
}
#Override
public void run(String[] args) throws Exception {
service.save(new String[] {"dummy_str", "dummy_str"});
}
}
**ExecuteI**
package com.test_4.test4;
import org.springframework.boot.CommandLineRunner;
public interface ExecuteI extends CommandLineRunner {
void run(String... args) throws Exception;
}
**NonWebService**
package com.test_4.test4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class NonWebService {
private final RandomTableREPO randomTableREPO;
#Autowired
public NonWebService(RandomTableREPO randomTableREPO) {
this.randomTableREPO = randomTableREPO;
}
public void save(String... dummyArgs) {
this.randomTableREPO.save(new RandomTableEntity());
System.out.println("\n\n+++++++++++++++++++++++++++++++++++++");
}
}
**RandomTableREPO**
package com.test_4.test4;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface RandomTableREPO extends JpaRepository<RandomTableEntity, Integer> {
}
**application.properties**
spring.main.web-application-type=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/test3
spring.datasource.username=postgres
spring.datasource.password=
spring.jpa.show-sql=true
have also RandomTableEntity.class, but i think for the described problem is not neccesary.
I accessed several links, but I still didn't find an answer to my error.
Until i've created and tried to use RandomTableREPO, i reached the save() method in NonWebService.class, but couldn't insert an object in database... any help from the enlightened minds in spring boot?
I want to have an object saved in database, using RandomTableREPO interface, which extends JpaRepository

Spring Boot not finding RestController

So I've got a simple spring boot app, #SpringBootApplication, a stub #Configuration and a #RestController all in the same package. Spring-boot-web-starter is there and the webserver comes up fine, actuator endpoints and all. But I cannot for the life of me get the app to pick up the #RestControllers.
enter image description here
Main.class:
package com.iglossolalia.munin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(MuninContext.class, args);
}
}
MuninContext.class:
package com.iglossolalia.munin;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
public class MuninContext {
}
MuninService.class:
package com.iglossolalia.munin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MuninService {
private static final Logger LOG = LoggerFactory.getLogger(MuninService.class);
public MuninService() {
LOG.info("Started MuninService");
}
#GetMapping("/health")
public String healthCheck() {
return "pong";
}
}
Tried explicitly adding the rest controller to the component scan with no luck there.
You have no #ComponentScan annotation in your MuninContext. Actually you can write SpringApplication.run(Main.class, args) in main method as Spring Initializr generate by default, you don't really need your context, because #SpringBootApplication work as configuration and contains #EnableAutoConfiguration, #ComponentScan, and some other annotations. Otherwise, as you pass your config class as argument in SpringApplication.run method, annotation #SpringBootApplication in Main class has no effect

Spring Boot #Autowired object - Nullpointer Exception [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 3 years ago.
I am developing a spring boot application to send sms notification. This is my class for the purpose.
package org.otp.services;
import org.otp.Configurations;
import com.mashape.unirest.http.HttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
#Component
public class SmsService
{
private static final Logger LOG = LoggerFactory.getLogger(SmsService.class);
public String send(String mobile, String msg)
{
//Code
}
}
And this is the class which uses the above class for sending notification.
package org.otp.controllers;
import org.otp.Constants;
import org.otp.services.EmailService;
import org.otp.services.SmsService;
import org.otp.dto.MessageRequest;
import org.otp.dto.MessageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
#Component
public class MessageController {
private static final Logger LOG = LoggerFactory.getLogger(MessageController.class);
#Autowired
SmsService smsService;
public void sendMessageToAlert(#RequestBody MessageRequest messageRequest)
{
String smsStatus = "FAIL";
MessageResponse messageResponse = new MessageResponse();
//1. Nullpointer
smsStatus = smsService.send(messageRequest.getMobileNo(),messageRequest.getMessage());
}
}
Main Class
package org.otp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
#SpringBootApplication
#EnableAsync
public class OtpServiceApplication implements ApplicationRunner
{
public static void main(String[] args) {
SpringApplication.run(OtpServiceApplication.class, args);
}
}
Problem is, I get a nullpointer exception in the (1) stating that my SmsService object is null. And my main class is in package org.otp so the two classes here falls under sub package so no need of component scan.
Therefore I am confused what to do to solve this. I have tried many answers here like adding a #Component annotation and #ComponentScan in main class but nothing works. Could someone please point out my mistake here.
Thanks in advance.
If your #Autowired annotation is not working and throws NPE ,it means that spring fails to create an instance of the component class in the application context . Try to:
Verify that the classes are in class path for scanning and also check to ensure that all auto-wired classes have the annotation #Component to enable them to be picked up during class path scanning.
Check the spring boot start up logs to verify if there are any errors
during bean creation.
Check to ensure all related classes used in the service layer are auto-wired properly and that the injected classes are annotated with #Component .
For further help please share the main application class along with your project structure.
Since you are using springboot , it is preferable to use the sprinboot stereotype annotations instead of the #Component annotation, if you are building a standard springboot web application.
#Service : for the service layer.
#Controller : for the controller layer . Also,DispatcherServlet will look for #RequestMapping on classes which are annotated using #Controller but not with #Component.
In Springboot application's main class add following annotation
#SpringBootApplication
#ComponentScan(
basePackages = {"org.otp.*"}
)
public class YourSpringMainClass{
public static void main(String[] args) {
SpringApplication.run(YourSpringMainClass.class, args);
}
}
While using annotations we should configured with #ComponentScan annotation to tell Spring the packages to scan for annotated components. This should be used in mail class(Which class wants to load first) in your case you are working with spring boot so you should use this annotation in Springboot application's main class. Like below
#SpringBootApplication
#ComponentScan(
basePackages = {"org.otp.*"}
)
public class YourSpringMainClass{
public static void main(String[] args) {
SpringApplication.run(YourSpringMainClass.class, args);
}
}

Parameter 0 of method init in com.ayman.image.Main required a bean of type 'com.ayman.image.storage.StorageService' that could not be found

I have a Spring app. I am using Eclipse IDE on Windows.
When initiating my Spring app I am instantiating my app with StorageService Interface.
package com.ayman.image;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.ayman.image.storage.StorageService;
#SpringBootApplication
#ComponentScan("com.ayman.image.storage") //added this line by myself
public class Main{
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
#Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
When running this Spring App I am getting the error
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method init in com.mastercard.ayman.image.Main required a
bean of type 'com.mastercard.ayman.image.storage.StorageService' that could
not be found.
Action:
Consider defining a bean of type
'com.ayman.image.storage.StorageService' in your configuration.
I have defined my Bean using component scan. Is this the wrong approach?
The problem may come from StorageService not being a Spring bean. If the bean is not defined with pertinent spring annotations, you should initialize it in the same way as you did with CommandLineRunner.
change it like that it works for me
public class SpringBootSecurityJwtApplication implements CommandLineRunner {
#Resource
FilesStorageService storageService;
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityJwtApplication.class, args);
System.out.println("version: " + SpringBootVersion.getVersion());
}
#Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}

Java Spring Boot - routing for access to static folder

I am working on a reactjs project and I just did a yarn build and moved the contents into the Java project.
my-project\complete\src\main\resources\static
but when I view the project from the Java site -- localhost:8080 -- I get a ton of 404 errors
logo.a67f8998.png:1 GET http://localhost:8080/static/media/logo.a67f8998.png
registerServiceWorker.js:77 GET http://localhost:8080/service-worker.js 404
-beefeater.78e4414b.jpg:1 GET http://localhost:8080/static/media/-beefeater.78e4414b.jpg 404 ()
For this project I am mostly acting as a frontend dev - Where do I make the required changes to get the routing correct for these files?
my Application.java file looks like this - when I uncomment the code I get told to remove the #overide?
//import java.util.Date;
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.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
/**
* Hello world!
*
*/
#SpringBootApplication
public class Application implements CommandLineRunner {
//#Autowired
//private AccountRepository accountRepository;
/**
* #param args
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... arg0) throws Exception {
}
/*
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}*/
}
I've tried to add a config file to sort this out.. do I need to import it in the application.java?
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//#Configuration
#EnableWebMvc
#WebAppConfiguration
public class Configuration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
You're missing #WebMvcAutoConfiguration annotation I think

Categories