Spring Boot set up Two Datasources gives Autoconfiguration error - oracle

I'm trying to configure two datasources in my spring boot app but by doing that I'm not sure if the Autoconfiguration option of spring should be turn off or if I'm missing some code.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pe.com.test</groupId>
<artifactId>Dashboard</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
# Oracle settings
#DB1
db1.datasource.url=jdbc:oracle:thin:#192.168.1.2:1521:DB1
db1.datasource.username=test
db1.datasource.password=abc123
db1.datasource.driver.class=oracle.jdbc.driver.OracleDriver
#DB2
db2.datasource.url=jdbc:oracle:thin:#192.168.1.3:1521:DB2
db2.datasource.username=test
db2.datasource.password=abc123
db2.datasource.driver.class=oracle.jdbc.driver.OracleDriver
My config class.
#Configuration
public class DataSourceConfiguration {
#Bean
#Primary
#ConfigurationProperties("db1.datasource")
public DataSource db1Ds() {
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties("db2.datasource")
public DataSource db2Ds() {
return DataSourceBuilder.create().build();
}
#Bean
#Autowired
#Primary
DataSourceTransactionManager db1Tm(#Qualifier("db1Ds") DataSource dataSource) {
DataSourceTransactionManager dstm = new DataSourceTransactionManager(dataSource);
return dstm;
}
#Bean
#Autowired
DataSourceTransactionManager db2Tm(#Qualifier("db2Ds") DataSource dataSource) {
DataSourceTransactionManager dstm = new DataSourceTransactionManager(dataSource);
return dstm;
}
}
I know that since I'm changing the default properties for autoconfiguring the database spring.datasource when starting the app It should give an error.
2020-04-04 16:02:25.654 WARN 15076 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2020-04-04 16:02:25.665 INFO 15076 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-04-04 16:02:25.667 ERROR 15076 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1
I can bypass these error just by turning off spring autoconfiguration.
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
What I want to know if I'm on the right path by turning DataSourceAutoConfiguration off or if I'm missing some other configuration in order to make autoconfigure work.

Better try with these database properties and configurations
#DB1
spring.db1-datasource.url=jdbc:oracle:thin:#192.168.1.2:1521:DB1
spring.db1-datasource.username=test
spring.db1-datasource.password=abc123
spring.db1-datasource.driver.class=oracle.jdbc.driver.OracleDriver
#DB2
spring.db2-datasource.url=jdbc:oracle:thin:#192.168.1.3:1521:DB2
spring.db2-datasource.username=test
spring.db2-datasource.password=abc123
spring.db2-datasource.driver.class=oracle.jdbc.driver.OracleDriver
#Configuration
public class DataSourceConfiguration {
#Bean
#Primary
#ConfigurationProperties(prefix="spring.db1-datasource")
public DataSource db1Ds() {
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties(prefix="spring.db2-datasource")
public DataSource db2Ds() {
return DataSourceBuilder.create().build();
}
#Bean
#Autowired
#Primary
DataSourceTransactionManager db1Tm(#Qualifier("db1Ds") DataSource dataSource) {
DataSourceTransactionManager dstm = new DataSourceTransactionManager(dataSource);
return dstm;
}
#Bean
#Autowired
DataSourceTransactionManager db2Tm(#Qualifier("db2Ds") DataSource dataSource) {
DataSourceTransactionManager dstm = new DataSourceTransactionManager(dataSource);
return dstm;
}
}

Related

SpringBoot - Unsatisfied dependency expressed through field

I was trying for CRUD services using springboot with mongodb.
Getting error while running main application.
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productServiceImpl'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cts.eaution.impl.ProductServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Controller class :
#RestController
#RequestMapping("/e-auction/api/v1/seller/")
public class ProductController {
#Autowired
public ProductServiceImpl productServiceImpl;
/* #Autowired
public ProductRepository productRepository;
*/
#GetMapping("/show-bids")
public List<Product> getAllProducts() {
System.out.println("Hello Product...");
return productServiceImpl.findAll();
//return productRepository.findAll();
}
}
ServiceImpl class :
class ProductServiceImpl implements ProductService {
#Autowired
private ProductRepository productRepository;
#Override
public List<Product> findAll() {
return productRepository.findAll();
}
}
Service interface :
#Service
public interface ProductService {
List<Product> findAll();
}
Repository interface :
public interface ProductRepository extends MongoRepository<Product, String> {
}
Pom xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!-- <version>2.7.5</version> -->
<version>2.6.13</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cts</groupId>
<artifactId>eauction</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eauction</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I tried multiple option by adding annotation like (service, repository, component, componentscan) non of this solve the problem.
application properties :
#server
server.port=8082
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=productdb
Full Error logs :
Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productServiceImpl': Unsatisfied dependency expressed through field 'productRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository' defined in com.cts.eauction.repository.ProductRepository defined in #EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoDatabaseFactorySupport]: Factory method 'mongoDatabaseFactory' threw exception; nested exception is java.lang.IllegalArgumentException: Database name must not contain slashes, dots, spaces, quotes, or dollar signs!
You have to place the #Service annotation on the implementation and not on the interface in order to make it autodetected by the component scan. Like this:
#Service
class ProductServiceImpl implements ProductService {
#Autowired
private ProductRepository productRepository;
#Override
public List<Product> findAll() {
return productRepository.findAll();
}
}
Also you should ask for a bean of the interface type and not the implementation in your controller:
#RestController
#RequestMapping("/e-auction/api/v1/seller/")
public class ProductController {
#Autowired
public ProductService productService;
}
This way you can have different implementations of the same interface, also you should not use field injection unless you have a good reason to use it.
If the above solution didn't work then another way you can try is by putting -
#ComponentScan(basePackages = {"com.package.class", "com.package.anotherClass"})
in your main application class.
This will scan all your classes present inside the packages.

Could not load JDBC driver class [com.mysql.cj.jdbc.Driver]

I've got the following class in my Spring Boot app:
#Configuration
public class JDBCTokenConfig {
...
#Value("${spring.datasource.driver-class-name}")
private String dbDriverClassName;
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbDriverClassName);
dataSource.setUrl(datasourceUrl);
dataSource.setUsername(dbUsername);
dataSource.setPassword(dbPassword);
return dataSource;
}
I've also got the following in my pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
In my application.properties I have:
...
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Yet I'm seeing the following error:
Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.cj.jdbc.Driver]
Is this the correct the drive class path? Or anything else?
Try using com.mysql.jdbc.Driver
Spring uses the following preconfigured versions for dependencies when a version is not explicitly provided in the pom.xml:
https://docs.spring.io/platform/docs/current/reference/htmlsingle/#appendix-dependency-versions
Here the following version of mysql-connector-java will be used . 5.1.47
For mysql-connector-java v5.1.47 the correct driver class is com.mysql.jdbc.Driver
You could also provide the dependency with version to use the latest driver : com.mysql.cj.jdbc.Driver
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>

Why does Spring Boot app start when two #Bean methods are present for restTemplate

I have this dependency:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
And I have this config:
#Configuration
public class AppConfig {
#Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(ofMillis(3000))
.setReadTimeout(ofMillis(3000))
.build();
}
}
I wonder why Spring does not fail on start. It never inits first restTemplate but inits second one. I would expect Spring to fail.
This is a valid case, you are defining two bean definitions with same name of same bean, then the last bean defined will replace then first one bean defined.
If you want to an exception is thrown when two beans are defined by same name then you can configure by using setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) method from DefaultListableBeanFactory is who overrides whether it should be allowed to override bean definitions by registering a different definition with the same name.

Error creating bean with name 'gemfireCache': FactoryBean threw exception on object creation

I am trying to create an "employee" Region and put some data into it. But, I am getting Exception below:
[warn 2018/12/27 17:15:46.518 IST tid=0x1] Exception
encountered during context initialization - cancelling refresh
attempt: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'gemfireConfiguration': Injection of
resource dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'gemfireCache': FactoryBean threw exception on
object creation; nested exception is java.lang.NoClassDefFoundError:
it/unimi/dsi/fastutil/ints/Int2ObjectOpenHashMap
[warn 2018/12/27 17:15:46.519 IST tid=0x1] Invocation of
destroy method failed on bean with name 'gemfireCache':
org.apache.geode.cache.CacheClosedException: A cache has not yet been
created.
[error 2018/12/27 17:15:46.522 IST tid=0x1] Caught exception
while allowing TestExecutionListener
[org.springframework.test.context.web.ServletTestExecutionListener#c667f46]
to prepare test instance
[com.gemfire.demo.Gemfire1ApplicationTests#48bfb884]
Domain class
#Region("employee")
public class Employee {
#Id
public String name;
public double salary;
...
}
Repository class
#Repository
public interface EmployeeRepository extends CrudRepository<Employee, String> {
Employee findByName(String name);
}
Configuration class
#Configuration
#ComponentScan
#EnableGemfireRepositories(basePackages = "com.gemfire.demo")
public class GemfireConfiguration {
#Autowired
EmployeeRepository employeeRepository;
#Bean
Properties gemfireProperties() {
Properties gemfireProperties = new Properties();
gemfireProperties.setProperty("name", "SpringDataGemFireApplication");
gemfireProperties.setProperty("mcast-port", "0");
gemfireProperties.setProperty("log-level", "config");
return gemfireProperties;
}
#Bean
#Autowired
CacheFactoryBean gemfireCache() {
CacheFactoryBean gemfireCache = new CacheFactoryBean();
gemfireCache.setClose(true);
gemfireCache.setProperties(gemfireProperties());
return gemfireCache;
}
#Bean(name="employee")
#Autowired
LocalRegionFactoryBean<String, Employee> getEmployee(final GemFireCache cache) {
LocalRegionFactoryBean<String, Employee> employeeRegion = new LocalRegionFactoryBean<String, Employee>();
employeeRegion.setCache(cache);
employeeRegion.setClose(false);
employeeRegion.setName("employee");
employeeRegion.setPersistent(false);
employeeRegion.setDataPolicy(DataPolicy.PRELOADED);
return employeeRegion;
}
}
POM.XML
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-gemfire</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.0</version>
</dependency>
Adding additional tips with your above GemFire/Spring JavaConfig configuration class above.
Given you are using Spring Data Kay (implied by your use of the Spring Boot 2.0.x parent POM, i.e. org.springframework.boot:spring-boot-dependencies; see here), then you could be using Spring Data GemFire's (relatively) new and convenient Annotation-based configuration model.
By doing so, your GemfireConfiguration class above would become...
#PeerCacheApplication
#EnableGemfireRepositories(basePackages = "com.gemfire.demo")
class GemfireConfiguration {
#Bean(name="employee")
LocalRegionFactoryBean<String, Employee> getEmployee(GemFireCache cache) {
LocalRegionFactoryBean<String, Employee> employeeRegion =
new LocalRegionFactoryBean<String, Employee>();
employeeRegion.setCache(cache);
employeeRegion.setClose(false);
employeeRegion.setDataPolicy(DataPolicy.PRELOADED);
return employeeRegion;
}
}
A few things to keep in mind:
#PeerCacheApplication is meta-annotated with #Configuration so you do not need the explicit Spring #Configuration annotation on the configuration class.
#PeerCacheApplication allows you to adjust the GemFire log-level (along with other logging configuration) using the logLevel annotation attribute. Similarly, you can set the log-level using the corresponding property, spring.data.gemfire.cache.log-level in a Spring Boot application.properties file (see here). There are many other attributes and corresponding properties (e.g. name) you can use to adjust and customize other configuration.
While String-based package names are supported on #EnableGemfireRepositories and similar annotations, we generally prefer and recommend users to use the type-safe variant basePacakgeClasses. You only need to refer to a single type from each top-level package where your application Repositories are kept.
The explicit #Autowired annotation is not needed on your bean definitions. You do not need to explicit inject the EmployeeRepository in the configuration class to have it initialized; just inject it into the #Service class where it will be used.
For convenience, the name ("employee") of the Region bean definition on your LOCAL "employee" Region, will also be used as the name of the Region, so employeeRegion.setName("employee") is unnecessary.
You should not combine LocalRegionFactoryBean.setPersistent(:boolean) with LocalRegionFactoryBean.setDataPolicy(:DataPolicy) since the DataPolicy is going to take precedence.
While #ComponentScan is perfectly acceptable and even convenient in development, I generally do not prefer nor recommend users to use component-scanning. It is usually always better to be explicit.
As stated in the comments, you chould remove <relativePath/> from your parent definition in your application Maven POM file.
Final note, as of this post, Spring Boot 2.0.8.RELEASE is the latest release.
As for your classpath issues, if you are using Maven correctly, then Maven should take care of pulling in the correct transitive dependencies.
You can refer to the many examples I have in this repo for further clarification.
Hope this helps!
As mentioned in comments, the error shows some dependencies (java.lang.NoClassDefFoundError: it/unimi/dsi/fastutil/ints/Int2ObjectOpenHashMap) are missing. Please add corresponding dependencies in your pom.xml

No bean named 'transactionManager' available

When I tried to create relationship using spring code,
I am getting Transaction manager error. I am using Mysql and Neo4j database in my project. I tries different solution but not able to resolve.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'transactionManager' available: No matching
PlatformTransactionManager bean found for qualifier
'transactionManager' - neither qualifier match nor bean name match!
Pom.xml file as below
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.10.RELEASE</version>
</dependency>
<!-- For Neo4J Graph Database -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.9-rc</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.5.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
</project>
Application.class
#SpringBootApplication
#EnableTransactionManagement
#EntityScan("projectone.entities")
public class Application {
public static void main(String[] args) {
//For Starting application
ApplicationContext applicationContext=SpringApplication.run(Application.class, args);
}
}
Database Configuration file:
#Configuration
#EnableJpaRepositories(basePackages = {"projectone.mysql"},
entityManagerFactoryRef = "dbEntityManager",
transactionManagerRef = "dbTransactionManager")
#EnableTransactionManagement
public class DatabaseConfiguration {
#Autowired
private Environment env;
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean dbEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dbDatasource());
em.setPackagesToScan(new String[]{"projectone.mysql"});
em.setPersistenceUnitName("dbEntityManager");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect",env.getProperty("hibernate.dialect"));
properties.put("hibernate.show-sql",env.getProperty("jdbc.show-sql"));
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean
public DataSource dbDatasource() {
DriverManagerDataSource dataSource
= new DriverManagerDataSource();
dataSource.setDriverClassName(
env.getProperty("spring.datasource.driverClassName"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
#Primary
#Bean
public PlatformTransactionManager dbTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
dbEntityManager().getObject());
return transactionManager;
}
}
I tried minimal configuration by removing the database configuration class. After that my application is not running and I am getting Person is not a managed Bean error.
If I use only #SpringBootApplication annotation then I am getting following Exception:
It is throwing
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingController': Unsatisfied dependency expressed through field 'branchService';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'branchServiceImplementaion': Unsatisfied dependency expressed through field 'branchRepository';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'branchRepository': Unsatisfied dependency expressed through method 'setSession' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.neo4j.transaction.SharedSessionCreator#0': Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.class]: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is NullPointerException
Finally I found the mistake:
#Bean
public PlatformTransactionManager dbTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
dbEntityManager().getObject());
return transactionManager;
}
This section has mistake that caused the above issue.
change #Bean to #Bean(name="transactionManager") and this solved the issue.
I had the same issue, but I was missing the transactionManagerRef = "dbTransactionManager" configuration in #EnableJpaRepositories
resolve: to change a name of function from:
public PlatformTransactionManager dbTransactionManager(){}
to:
public PlatformTransactionManager transactionManager(){}
Checke transactionManager this name JPAConfig class.
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
return new JpaTransactionManager(emf);
}
I had the same problem and I noticed that there is an extra space where while specifying the transaction-manager as specified in the image.

Resources