SpringBoot scanBasePackages does not find repository in different jar - java

I have a spring boot application like this:
package my.package;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
#SpringBootApplication
public class MySpringBootApp{
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class, args);
}
}
I have a service in the package my.package.service
#Service
public class MyService {
private ServiceInADifferentJar dep;
public MySerivce(ServiceInADifferentJar dep) {
this.dep = dep;
}
}
The class ServiceInADifferentJar is an #Service annotated class in a different JAR, which I include as a maven dependency.
The JAR Has this file structure:
src/main/java
- some.package.repository
MyRepository.java
- some.package.service
ServiceInADifferentJar.java
MyRepository is an #Repository annotated interface that extends a Spring Data inerface.
ServiceInADifferentJar gets MyRepository injected in its constructor.
WHen I start the application, I get an error that ServiceInADifferentJar cannot be found.
Then I added this to my SpringBootApp
#SpringBootApplication(scanBasePackages = {"some.package"})
andServiceInADifferentJar is found, but not MyRepository.
Why not? Why aren't all sub-packages of some.package in the other JAR scanned?
* EDIT *
The repository
package some.package.repository;
#Repository
public interface MyRepository extends MongoRepository<SomeEntity, String> {
}

You may want to use the EnableMongoRepositories annotation, so that your Mongo repository gets found .
#EnableMongoRepositories(basePackages = "some.package.repository")
The following question, despite being about JPA repositories, has some more explanation about how repositories scanning work :
Can't Autowire #Repository annotated interface in Spring Boot

hey man you should put this in your main class after the #SpringBootApplication tag
#ComponentScan(basePackages = {"some.package"})

Related

CommandLineRunner Never Executes (Spring Boot 2.6.7)

I am trying to learn Spring Boot and restful application from an online tutorial. But the code I wrote for it somehow gives me an error. I have written a CommandLineRunner class like so:
package com.trial.cas.preload;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import com.trial.cas.employee.repository.EmployeeRepository;
import com.trial.cas.employee.pojo.Employee;
#Configuration
class LoadDatabase implements CommandLineRunner {
private static final Logger log = java.util.logging.LogManager.getLogManager().getLogger("LoadDatabase");
#Autowired
EmployeeRepository employeeRepository;
#Override
public void run(String... args) throws Exception {
log.info("Preloading " + employeeRepository.save(new Employee("Bilbo Baggins", "burglar")));
log.info("Preloading " + employeeRepository.save(new Employee("Frodo Baggins", "thief")));
}
}
My EmployeeRepository class is like this:
package com.trial.cas.preload;
import org.springframework.data.jpa.repository.JpaRepository;
import com.trial.employee.pojo.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
My main class is written like:
package com.trial.cas.logging.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class CASLoggingToolApplication {
public static void main(String[] args) {
SpringApplication.run(CASLoggingToolApplication.class, args);
}
}
But when I run the Spring Boot application, the lines in the run method never execute. I have a debug point point in the first line of the run method. But that never gets triggered.
Please help! Thanks in advance.
By default Spring Boot will only scan packages below the package of the main application class (in your example it would be the package com.trial.cas.logging.example and all subpackages.
You can either move the application class to a common super package for your application, or specify all other packages, that should be scanned for beans etc. on the annotation:
#SpringBootApplication(scanBasePackages = {"com.trial.cas.logging.example", "com.trial.cas.preload"})
Try using #Component instead of #Configuration when annotating your LoadDatabase class.
Also, if I recall correctly, for Spring Boot to run properly it is necessary to annotate your EmployeeRepository with #Repository.
Another last tip, try to avoid field injections like:
#Autowired
EmployeeRepository employeeRepository;
It has several drawbacks compared to constructor injection, which are described in detail in this answer: What exactly is Field Injection and how to avoid it?
Instead use constructor injection, like this:
private EmployeeRepository employeeRepository;
#Autowired
public LoadDatabase(EmployeeRepository employeeRepository){
this.employeeRepository = employeeRepository;
}

Consider defining a bean of type 'packagepath' in your configuration

I am getting the following error:
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in mn.ailab.bankcg.cashout.service.bankservice.BankSelector required a bean of type 'mn.ailab.bankcg.cashout.service.bankservice.CgwBankRepository' that could not be found.
Action:
Consider defining a bean of type 'mn.ailab.bankcg.cashout.service.bankservice.CgwBankRepository' in your configuration.
My project structure:
Project Structure
I have configured base packages:
#ComponentScan(basePackages = {"mn.ailab", "mn.invescore.ailab"})
#EnableJpaRepositories(basePackages = {"mn.ailab", "mn.invescore.ailab"})
#EntityScan(basePackages = {"mn.ailab", "mn.invescore.ailab"})
#SpringBootApplication
#EnableCaching
#EnableScheduling
public class AccountingApplication {
public static void main(String[] args) {
SpringApplication.run(AccountingApplication.class, args);
}
}
CgwBankRepository.java
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
interface CgwBankRepository extends CrudRepository<CgwBank, String> {
List<CgwBank> findAllBy();
}
I have changed base package different ways. But still get same error.

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);
}
}

Spring boot says it requires a certain bean

This is the userService class that requires a bean of type com.example.repository.userRepository that could not be found
package com.example.services;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.modal.User;
import com.example.repository.userRepository;
#Service
#Transactional
public class UserService {
#Autowired
private userRepository userRepository;
public UserService() {
super();
}
public UserService(userRepository userRepository)
{
this.userRepository = userRepository;
}
public void saveMyuser(User user) {
userRepository.save(user);
}
}
The error message reads :
Consider defining a bean of type 'com.example.repository.userRepository' in your configuration.
This is the repository:
package com.example.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.modal.User;
public interface userRepository extends CrudRepository<User,Integer> {
}
this is the application class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
public class TutorialProjectApplication {
public static void main(String[] args) {
SpringApplication.run(TutorialProjectApplication.class, args);
}
}
Seems like userRepository interface is outside of spring-boot default scanning i.e. package of that repository interface is not same or sub-package of the class annotated with #SpringBootApplication. If so, you need to add #EnableJpaRepositories("com.example.repository") on your main class.
Update:
After looking at your updated post, you need to add #EnableJpaRepositories("com.example.repository") to TutorialProjectApplication class
Always keep the #SpringBootApplication main class outer package so that it will automatically scan all the subpackages.
In your case you have main class in package com.example.demo; but the repository in package com.example.repository; which are different packages.so spring boot is not able to find the repositories.
So you have to make spring boot aware of the repositories location.
So now you have 2 solutions.
1.Either put repository class in subpackges of Main class package.
2.Or use #EnableJpaRepositories("com.example.repository") in main class.
In your repository you need to annotate the class
#Repository
public interface userRepository extends CrudRepository<User,Integer> {
}

#ComponentScan doesn't work in Spring boot AutoConfiguration class?

I am trying to create a new starter. I have a business module, say ProjectManager, that contains some classes annotated with #Component. Following the tutorial, I created an autoconfigure module, it contains an AutoConfiguration class. Firstly, I tried to use #ComponentSan to find the beans in my business module.
#ComponentScan(value = {"com.foo.project"})
#ConditionalOnClass({Project.class})
#Configuration
public class ProjectAutoConfiguration {
....
}
But it doesn't work. I have to add additional configuration class as below:
#Configuration
#ComponentScan(value = {"com.foo.project"})
#MapperScan(value = {"com.foo.project"})
public class ProjectConfig {
}
And then import it into AutoConfiguration class like below:
#Import(ProjectConfig.class)
#ConditionalOnClass({Project.class})
#Configuration
public class ProjectAutoConfiguration {
....
}
That works. But according to the spring doc.
auto-configuration is implemented with standard #Configuration classes
So my question is, Why #ComponentScan doesn't work here ? Did I make something wrong? Or it is by design ?
you have to use the compentscan annotation into the main class. Here a sample code:
#SpringBootApplication
#ComponentScan("com.foo.project")
public class MainApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MainApplication.class);
}
public static void main(String[] args) {
new MainApplication().configure(new SpringApplicationBuilder(MainApplication.class)).run(args);
}
}
Cheers
Automatic everything requires the Application class (annotated with #SpringBootApplication) to be in a "higher" package than the components you want to scan.
Use:
package com.example.foo;
for your application and put components in a package like:
package com.example.foo.entities;
See also https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html
Can you try with following?
#ConditionalOnClass({Project.class})
#Configuration
#EnableAutoConfiguration
#ComponentScan(value = {"com.foo.project"})
public class ProjectAutoConfiguration {
....
}
I was developing a SDK project. It needs the application which depends on the SDK to scan for beans beneath specific package in the SDK during start period.
Anotate with #ComponentScan on autowire configuration class doesn't take effect.
Then I am trying to use #Import annotation to import a class implemented interface ImportBeanDefinitionRegistrar(Interface to be implemented by types that register additional bean definitions when processing #Configuration classes. Useful when operating at the bean definition level (as opposed to #Bean method/instance level) is desired or necessary).
Within ImportBeanDefinitionRegistrar implementation class, I register a class annotated with #ComponentScan as bean. Run application again, it works as expected.
Codes below:
AutoConfiguration Class:
#Configuration
#Import(TestConfigRegistar.Registrar.class)
public class TestClientAutoCofiguration {
}
Registar class:
public class TestConfigRegistar {
public static class Registrar implements ImportBeanDefinitionRegistrar {
private static final String BEAN_NAME = "componentScanConfig";
#Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata,
BeanDefinitionRegistry registry) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(ComponentScanConfig.class);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinition.setSynthetic(true);
registry.registerBeanDefinition(BEAN_NAME, beanDefinition);
}
}
}
Class with #ComponentScan annotation
// Leave an empty value of #ComponentScan will let spring scan
// current class package and all sub-packages
#ComponentScan
public class ComponentScanConfig {
}
I believe that the point is that beans annotated with #ComponentScan must be defined at definition level (as opposed to #Bean method/instance level). Please correct me if I'm wrong, Thanks.

Categories