a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found - spring-boot

I am using spring boot 2.0.7 Release and spring-boot-starter-mail-2.0.7.Release.
I am autowiring javaMailsender inside the class working ok on windows while trying to deploy on Unix getting belwo issue
APPLICATION FAILED TO START
***************************
Description:
Field javaMailSender in com.fti.di.capstock.tran.pub.email.SendEmail required a bean of type 'org.springframework.mail.javamail.JavaMailSender' 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 'org.springframework.mail.javamail.JavaMailSender' in your configuration.
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;
import com.fti.di.capstock.tran.pub.constants.ApplicationFlowConstants;
import com.fti.di.integration.constants.IntegrationConstants;
import com.fti.di.integration.util.StringUtil;
#Component("sendEmail")
public class SendEmail {
#Autowired
private JavaMailSender javaMailSender;
#Autowired
Environment env;
#ServiceActivator

you've to provide the mail configuration in application.properties
spring.mail.host=MAIL_SERVER_IP
spring.mail.port=MAIL_SERVER_PORT
spring.mail.userName=USER_NAME
spring.mail.password=THE_PASSWORD
and if authentication not enable in server then
remove userName and password and add this
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
#Configuration
public class Config {
#Bean
public JavaMailSender javaMailSender() {
return new JavaMailSenderImpl();
}
}
You can also return an instance of JavaMailSenderImpl() from your #Bean above saving you the hustle of having to implement a bunch of methods when you try to return the actual JavaMailSender() class.

Declare a #Bean of the type JavaMailSender in a Configuration class (This is useful when you want to inject a class which is not part of your Spring Context, like a class that belongs to a 3rd-party lib, which happens to be your case). For example:
#Configuration
public class MyConfig {
#Bean
public JavaMailSender javaMailSender() {
return new JavaMailSender();
}
}
Make sure that the you have set the right properties under application.properties as well.
Also, take a look into this question, as I believe this is a duplicate (if it's not, I am sorry)

In My project i was reading email properties file like hostname, port etc from spring config server (Spring cloud).
I was missing a dependency at client end. Once i added that Dependency.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
JavamailSender class able to read those properties and worked fine.
In spring boot we need not define JavaMailSender bean manually. spring boot does itself.

the best answer I ve found was to check if you have a type in your application.properties:
spring.mail.host
spring.mail.username
spring.mail.password
spring.mail.port
Check the response of gleidson cardoso da silva from Could not autowire org.springframework.mail.javamail.JavaMailSender

This error occurred due to the missing following properties in the application.yml file.
mail:
host: localhost
port: 1025
username: hello
password: hello
properties:
mail:
smtp:
ssl:
trust: "*"
auth: true
starttls:
enable: true
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000

I have this error and it was related to missing properties in application.yml in the test folder.

Related

Consider defining a bean of type 'reactor.core.scheduler.Scheduler' in your configuration

I'm using SpringBoot2, Spring5 in my Java micro service application. I have required dependencies including the Scheduler. Build is fine without any compilation error but during run time, I'm getting below error in PooledAsyncRunner:-
***************************** APPLICATION FAILED TO START
*************************** Description: Parameter 0 of constructor in com.connector.async.core.PooledAsyncRunner required a bean of type
'reactor.core.scheduler.Scheduler' that could not be found. Action:
Consider defining a bean of type 'reactor.core.scheduler.Scheduler' in
your configuration.
#Service
public class PooledAsyncRunner implements AsyncRunner {
private final Scheduler scheduler;
#Autowired
public PooledAsyncRunner(Scheduler scheduler) {
this.scheduler = scheduler;
}
}
Below is spring main application file where I have explicitly annotated auto-configuration:-
#SpringBootApplication
#EnableAutoConfiguration
public class MarketApplication {
}
I have reactor-core dependency as well in pom.xml.
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.1.8.RELEASE</version>
</dependency>
Please advise. Thanks

Another unnamed CacheManager already exists when using Hibernate L2 ehcache and spring boot enabledCache

I have an application that have more than 100 domain model i want to integrate ehcache and hibernate L2cache ,my application used ehcache for cache some of service s methods . my CacheConfiguration is like this
package org.roshan.framework.config;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;
#Configuration
#EnableCaching
#AutoConfigureAfter(value = {DatabaseConfiguration.class})
public class CacheConfiguration {
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;
#PreDestroy
public void destroy() {
log.info("Remove Cache Manager metrics");
log.info("Closing Cache Manager");
}
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache();
jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
.withExpiry(Expirations.timeToLiveExpiration(Duration.of(ehcache.getTimeToLiveSeconds(), TimeUnit.SECONDS)))
.build()
);
}
#Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
log.debug("Starting Ehcache");
return cm -> {
// some cache for using in method of service
cm.createCache("baseInfoCache", jcacheConfiguration);
cm.createCache("attachments", jcacheConfiguration);
};
}
}
in application.yml change hibernate cache config like this
spring:
devtools:
restart:
enabled: true
livereload:
enabled: true # we use gulp + BrowserSync for livereload
application:
name: roshanframework
jpa:
open-in-view: true
hibernate:
ddl-auto: none
properties:
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.generate_statistics: false
hibernate.dialect : org.hibernate.dialect.MySQL5Dialect
#hibernate.default_schema : ihsl
hibernate.show_sql : true
hibernate.current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
but when i start my application i get exception that i have 2 cachemanager how solve this problem .
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:90)
at org.hibernate.cache.spi.RegionFactory.start(RegionFactory.java:63)
at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:71)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:58)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
... 45 common frames omitted
Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:626)
at net.sf.ehcache.CacheManager.init(CacheManager.java:391)
at net.sf.ehcache.CacheManager.<init>(CacheManager.java:269)
at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:69)
... 51 common frames omitted
I dont know why two cache manager exist? how can change configuration to using one cache manager for both hibernate and methods?
I also ran into this problem recently.
Soln is to use "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory" as hibernate factory_class.
spring:
jpa:
properties:
hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory

Spring Boot 2.0.0.M2 and Spring Data Elasticsearch configuration

I'm trying to move my project to Spring Boot 2.0.0.M2.
This is my old Spring Data Elasticsearch configuration:
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
#Profile("production")
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.example.domain.repository.elasticsearch")
public class ElasticsearchConfig {
#Value("${elasticsearch.host}")
private String host;
#Value("${elasticsearch.port}")
private int port;
#Bean
public Client client() throws Exception {
return TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
}
#Bean
public ElasticsearchOperations elasticsearchTemplate() throws Exception {
return new ElasticsearchTemplate(client());
}
}
Right now I faced a following issue:
1. The method builder() is undefined for the type TransportClient
2. InetSocketTransportAddress cannot be resolved to a type
On the Maven classpath I have Spring Data Elasticsearch 3.0.0.M4:
How to properly configure current version of Spring Data Elasticsearch ?
UPDATED
For my tests I use Embedded Elasticsearch with a following application.properties:
#Elasticsearch
spring.data.elasticsearch.properties.http.enabled=true
spring.data.elasticsearch.properties.http.port=9250
spring.data.elasticsearch.properties.path.home=target/test-elasticsearch-db
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=60s
This is my ES test config:
#Profile("test")
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.example.domain.repository.elasticsearch")
public class ElasticsearchTestConfig {
}
Right now the test fails with a following error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.elasticsearch.client.Client' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:726) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:458) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
and
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.elasticsearch.client.Client' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1478) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1089) ~[spring-beans-5.0.0.RC2.jar:5.0.0.RC2]
What is wrong here and how to fix this ?
Spring Boot 2.0 uses Elasticsearch 5 which includes some breaking API changes. You would be shielded from those changes if you used Spring Boot's auto-configuration rather than trying to write your own.
All that's needed is a value for the spring.data.elasticsearch.cluster-nodes property. With that in place, Spring Boot will auto-configure both a TransportClient and an ElasticsearchTemplate.
Had similar issue when migrating from spring-boot 1.5.6 to 2.0.0. The reason seems to be previous support for embedded elasticsearch is not more supported and the same is reflected in spring-boot.
Previously leaving the following property empty
spring.data.elasticsearch.cluster-nodes
put the following into use
spring.data.elasticsearch.properties.path.home
and spring-boot created given directory in the target folder for embedded mode to run. With spring-boot 2.0.0 (spring-boot-autoconfigure-2.0.0.RELEASE.jar to be precise) cluster-nodes has become asserted for non-null value causing elasticsearchTemplate bean not to be created under the hood.
That is the reason why your app stop working so suddenly.

Can't Autowire #Repository annotated interface in Spring Boot

I'm developing a spring boot application and I'm running into an issue here. I'm trying to inject a #Repository annotated interface and it doesn't seem to work at all. I'm getting this error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springBootRunner': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pharmacy.persistence.users.dao.UserEntityDao com.pharmacy.config.SpringBootRunner.userEntityDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.pharmacy.config.SpringBootRunner.main(SpringBootRunner.java:25)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pharmacy.persistence.users.dao.UserEntityDao com.pharmacy.config.SpringBootRunner.userEntityDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 16 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 18 common frames omitted
Here is my code:
Main application class:
package com.pharmacy.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("org.pharmacy")
public class SpringBootRunner {
public static void main(String[] args) {
SpringApplication.run(SpringBootRunner.class, args);
}
}
Entity class:
package com.pharmacy.persistence.users;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class UserEntity {
#Id
#GeneratedValue
private Long id;
#Column
private String name;
}
Repository interface:
package com.pharmacy.persistence.users.dao;
import com.pharmacy.persistence.users.UserEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserEntityDao extends CrudRepository<UserEntity,Long>{
}
Controller:
package com.pharmacy.controllers;
import com.pharmacy.persistence.users.UserEntity;
import com.pharmacy.persistence.users.dao.UserEntityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HomeController {
#Autowired
UserEntityDao userEntityDao;
#RequestMapping(value = "/")
public String hello() {
userEntityDao.save(new UserEntity("ac"));
return "Test";
}
}
build.gradle
buildscript {
ext {
springBootVersion = '1.2.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
mainClassName = "com.pharmacy.config.SpringBootRunner"
jar {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
}
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-ws")
compile("postgresql:postgresql:9.0-801.jdbc4")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
application.properties:
spring.view.prefix: /
spring.view.suffix: .html
spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=abc123
I even compared my code with Accessing data jpa, and I'm running out of ideas what's wrong with this code.
Any help appreciated.
EDITED: I changed my code as suggested to look like above, and I'm not getting that error when I'm injecting my #Repository interface into another component. However, I have a problem now - my component cannot be retrieved (I used debugging). What I'm doing wrong so spring cannot find my component?
When the repository package is different to #SpringBootApplication/#EnableAutoConfiguration, base package of #EnableJpaRepositories is required to be defined explicitly.
Try to add #EnableJpaRepositories("com.pharmacy.persistence.users.dao") to SpringBootRunner
I had the same issues with Repository not being found. So what I did was to move everything into 1 package. And this worked meaning that there was nothing wrong with my code. I moved the Repos & Entities into another package and added the following to SpringApplication class.
#EnableJpaRepositories("com...jpa")
#EntityScan("com...jpa")
After that, I moved the Service (interface & implementation) to another package and added the following to SpringApplication class.
#ComponentScan("com...service")
This solved my issues.
There is another cause for this type of problem what I would like to share, because I struggle in this problem for some time and I could't find any answer on SO.
In a repository like:
#Repository
public interface UserEntityDao extends CrudRepository<UserEntity, Long>{
}
If your entity UserEntity does not have the #Entity annotation on the class, you will have the same error.
This error is confusing for this case, because you focus on trying to resolve the problem about Spring not found the Repository but the problem is the entity. And if you came to this answer trying to test your Repository, this answer may help you.
It seems your #ComponentScan annotation is not set properly.
Try :
#ComponentScan(basePackages = {"com.pharmacy"})
Actually you do not need the component scan if you have your main class at the top of the structure, for example directly under com.pharmacy package.
Also, you don't need both
#SpringBootApplication
#EnableAutoConfiguration
The #SpringBootApplication annotation includes #EnableAutoConfiguration by default.
I had a similar issue where I was receiving NoSuchBeanDefinitionException in Spring Boot (basically while working on CRUD repository), I had to put the below annotations on the main class:
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan(basePackages={"<base package name>"})
#EnableJpaRepositories(basePackages="<repository package name>")
#EnableTransactionManagement
#EntityScan(basePackages="<entity package name>")
Also, make sure you have the #Component annotations in place on the implementations.
In SpringBoot, the JpaRepository are not auto-enabled by default. You have to explicitly add
#EnableJpaRepositories("packages")
#EntityScan("packages")
#SpringBootApplication(scanBasePackages=,<youur package name>)
#EnableJpaRepositories(<you jpa repo package>)
#EntityScan(<your entity package>)
Entity class like below
#Entity
#Table(name="USER")
public class User {
#Id
#GeneratedValue
To extend onto above answers, You can actually add more than one package in your EnableJPARepositories tag, so that you won't run into "Object not mapped" error after only specifying the repository package.
#SpringBootApplication
#EnableJpaRepositories(basePackages = {"com.test.model", "com.test.repository"})
public class SpringBootApplication{
}
It could be to do with the package you have it in. I had a similar problem:
Description:
Field userRepo in com.App.AppApplication required a bean of type 'repository.UserRepository' 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 'repository.UserRepository' in your configuration.
"
Solved it by put the repository files into a package with standardised naming convention:
e.g. com.app.Todo (for main domain files)
and
com.app.Todo.repository (for repository files)
That way, spring knows where to go looking for the repositories, else things get confusing really fast. :)
Hope this helps.
You are scanning the wrong package:
#ComponentScan("**org**.pharmacy")
Where as it should be:
#ComponentScan("**com**.pharmacy")
Since your package names start with com and not org.
I had some problems with this topic too.
You have to make sure you define the packages in Spring boot runner class like this example below:
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan({"controller", "service"})
#EntityScan("entity")
#EnableJpaRepositories("repository")
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
I hope this helps!
Here is the mistake: as someone said before, you are using org.pharmacy insted of com.pharmacy in componentscan
package **com**.pharmacy.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("**org**.pharmacy")
public class SpringBootRunner {
If you're facing this problem when unit testing with #DataJpaTest then you'll find the solution below.
Spring boot do not initialize #Repository beans for #DataJpaTest. So try one of the two fix below to have them available:
First
Use #SpringBootTest instead. But this will boot up the whole application context.
Second(Better solutions)
Import the specific repository you need, like below
#DataJpaTest
#Import(MyRepository.class)
public class MyRepositoryTest {
#Autowired
private MyRepository myRepository;
I had a similar issue with Spring Data MongoDB: I had to add the package path to #EnableMongoRepositories
I resolved that issue by changing that dependency :
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
With that one :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
In that way there is no need to use Anotations like :
#EnableAutoConfiguration
#ComponentScan({"controller", "service"})
#EntityScan("entity")
#EnableJpaRepositories("repository")
)
I had a similar problem but with a different cause:
In my case the problem was that in the interface defining the repository
public interface ItemRepository extends Repository {..}
I was omitting the types of the template. Setting them right:
public interface ItemRepository extends Repository<Item,Long> {..}
did the trick.
In #ComponentScan("org.pharmacy"), you are declaring org.pharmacy package.
But your components in com.pharmacy package.
Many of the answer up there help a lot, because they are part of the whole solution. For me it was a mix of some of them.
Your ComponentScan package is wrong. Change it to:
#ComponentScan("com.pharmacy")
You also have to add:
#EnableJpaRepositories
to your SpringBootApplication class, here: SpringBootRunner.
I had to change the Maven dependency (works similarly for Gradle):
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
To:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Don't forget to refresh your dependencies.
Then I also had to change my imports in my Entity class to:
import jakarta.persistence.*;
Make sure the #Service or #Component that is trying to auto-wire the repository isn't in the same directory as your SpringApplication.class. Make sure it's in a subfolder like service/.
Sometimes I had the same issues when I forget to add Lombok annotation processor dependency to the maven configuration
Adding the below dependency on pom.xml solved the problem
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
If your main class is in com.example package your other class should which are in different packages should be called in com.example package;
i.e:Controller package
com.example.controller
AND
Your Main class should be in com.example not in com.example.main
if you gave the main class package as com.example.main then the other should be within that package e.g com.package.main.controller

instantiate a datasource using Spring's JdbcTemplate

I want to instantiate a Datasource in the Dao Class. I'm following the Spring tutorial http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html. This is my code snippet:
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.*;
public class JdbcUserDao implements UserDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
but I get a "DataSource cannot be resolved to a type".
How can I fix this?
You need to import it, that's all:
import javax.sql.DataSource;
What is the DataSource that you have configured in the Spring configuration? You should have a datasource library similar to org.apache.commons.dbcp.BasicDataSource in your project. The tutorial link http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html shows the configuration under section '13.2.1.2 JdbcTemplate best practices'.
Actions:
1) Check if you have the datasource library in your project. If you are using the DataSource mentioned in the tutorial (BasicDataSource) then ensure you have Apache commons DBCP library is in your classpath.
2) Ensure you have imported the same in your DAO class.
I solved this problem by adding 'org.springframework' dependencies in pom.xml file.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
In my case, I was facing problem with import methods itself like "The import org.springframework.jdbc cannot be resolved"

Resources