Multiple datasources spring boot - java

I have tried for literally hours to get this working, looking at the docs:
https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html
...various stackoverflow questions and as much other stuff as I can find. But, this is proving elusive (read, making me want to bash my head against a wall). Any help would be so, so welcome!
I need to connect to two different databases (sounds simple enough?) and I have a Spring Boot web application using the spring-boot-starter-data-jpa dependency which got things off the ground very nicely with a single data source. Now I need to talk to a second database and things have not been working. I thought I had it working for a while, but it turned out that everything was going to the primary database.
I'm currently trying to get this working on a separate 'cut down' project to try and reduce the number of moving parts, still not working though.
I have two #Configuration classes - one for each data source, here's the first:
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "firstEntityManagerFactory",
transactionManagerRef = "firstTransactionManager",
basePackages = {"mystuff.jpaexp.jpatest"})
public class DataConfiguration {
#Bean
#Primary
#ConfigurationProperties(prefix = "app.datasource1")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
#ConfigurationProperties("app.datasource1")
public DataSource firstDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder().
driverClassName("org.postgresql.Driver").
url("jdbc:postgresql://localhost:5432/experiment1").
username("postgres").
password("postgres").
build();
}
#Primary
#Bean
public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("mystuff.jpaexp.jpatest");
factory.setDataSource(firstDataSource());
factory.setPersistenceUnitName("ds1");
return factory;
}
#Primary
#Bean
public PlatformTransactionManager firstTransactionManager() {
return new JpaTransactionManager();
}
}
and here's the second:
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "secondEntityManagerFactory",
transactionManagerRef = "secondTransactionManager",
basePackages = {"mystuff.jpaexp.jpatest2"})
public class Otherconfiguration {
#Bean
#ConfigurationProperties(prefix = "app.datasource2")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties("app.datasource2")
public DataSource secondDataSource() {
return secondDataSourceProperties().initializeDataSourceBuilder().
driverClassName("org.postgresql.Driver").
url("jdbc:postgresql://localhost:5432/experiment2").
username("postgres").
password("postgres").
build();
}
#Bean
public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("mystuff.jpaexp.jpatest2");
factory.setDataSource(secondDataSource());
factory.setPersistenceUnitName("ds2");
return factory;
}
#Bean
public PlatformTransactionManager secondTransactionManager() {
return new JpaTransactionManager();
}
}
In each of the two packages mystuff.jpaexp.jpatest and mystuff.jpaexp.jpatest2 I have a simple #Entity and CrudRepository that should go together with the first and second datasources respectively.
I then have a main() to test things out:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class})
#ComponentScan("mystuff.jpaexp.*")
public class SpringbootCommandLineApp implements CommandLineRunner {
private final MyRepository myRepository;
private final OtherRepo otherRepo;
#Autowired
public SpringbootCommandLineApp(MyRepository myRepository, OtherRepo otherRepo) {
this.myRepository = myRepository;
this.otherRepo = otherRepo;
}
public static void main(String[] args) {
new SpringApplicationBuilder(SpringbootCommandLineApp.class)
.web(false)
.run(args);
}
#Override
public void run(String... args) throws Exception {
myRepository.save(new MyEntity("Goodbye or hello"));
myRepository.save(new MyEntity("What?"));
myRepository.save(new MyEntity("1,2,3..."));
myRepository.findAll().forEach(System.out::println);
otherRepo.save(new MyEntity2("J Bloggs"));
otherRepo.save(new MyEntity2("A Beecher"));
otherRepo.save(new MyEntity2("C Jee"));
otherRepo.findAll().forEach(x -> {
System.out.println("Name:" + x.getName() + ", ID: " + x.getId());
});
}
}
And lastly, some props in application.properties:
app.datasource1.driver-class-name=org.postgresql.Driver
app.datasource1.url=jdbc:postgresql://localhost:5432/experiment1
app.datasource1.username=postgres
app.datasource1.password=postgres
app.datasource2.driver-class-name=org.postgresql.Driver
app.datasource2.url=jdbc:postgresql://localhost:5432/experiment2
app.datasource2.username=postgres
app.datasource2.password=postgres
These have absolutely no effect -- things appear to still be configured by spring.datasource.* instead, which is obviously no use.
Final output:
2018-05-25 17:04:00.797 WARN 29755 --- [ 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.HibernateJpaAutoConfiguration': 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$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
2018-05-25 17:04:00.800 INFO 29755 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-25 17:04:00.803 ERROR 29755 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
Process finished with exit code 1
I know there's a lot of code here, sorry and thanks!

Well, it took a long time, I think there were multiple subtle problems and also some bits that could be simplified a little:
Only one DataSourceProperties was required - both datasources can use it
#ConfigurationProperties is needed on the DataSource bean definition, not the DataSourceProperties bean
I think the #ComponentScan("mystuff.jpaexp.*") annotation was incorrect, and replacing this with simply #ComponentScan seemed to fix picking up of some of the bean definitions
I had to inject an EntityManagerFactor into the JpaTransactionManager definition: return new JpaTransactionManager(secondEntityManagerFactory().getObject());
I added a JpaProperties bean, and explicity pulled those properties into a VendorAdapter
The VendorAdapter/JpaProperties changes looked like this (it seems odd that JpaProperties is vendor-independent yet it has a hibernateProperties on it?!):
#Bean
public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("...entity-package...");
factory.setDataSource(secondDataSource());
Map<String, String> props = new HashMap<>();
props.putAll(secondJpaProperties().getProperties());
props.putAll(secondJpaProperties().getHibernateProperties(secondDataSource()));
factory.setJpaPropertyMap(props);
factory.setPersistenceUnitName("ds2");
return factory;
}
#Bean
#ConfigurationProperties(prefix = "jpa.datsource2")
public JpaProperties secondJpaProperties() {
return new JpaProperties();
}
I think this was enough to get things going. In addition, the ever-so-clever defaulting of various properties to make an embedded H2 instance spring to life, no longer worked, so I also had to be explicit about all the DB properties:
jpa.datasource1.hibernate.ddl-auto=create
app.datasource1.driver-class-name=org.h2.Driver
app.datasource1.url=jdbc:h2:mem:primary
app.datasource1.username=
app.datasource1.password=
jpa.datasource2.hibernate.ddl-auto=create
app.datasource2.driver-class-name=org.h2.Driver
app.datasource2.url=jdbc:h2:mem:view
app.datasource2.username=
app.datasource2.password=

Related

Unresolveable Circular reference error when configuring multiple datasources in a spring batch

I'm trying to configure two datasources in my spring batch application. One for batch metadata tables, and another for the business tables.
Snippet from my application.properties file:
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=
spring.batchdatasource.url=
spring.batchdatasource.username=
spring.batchdatasource.password=
spring.batchdatasource.driver-class-name=
My batch config file:
#Configuration
public class SpringBatchConfig extends DefaultBatchConfigurer{
#Autowired
private JobBuilderFactory jobs;
#Autowired
private StepBuilderFactory steps;
// #Autowired
// private DataSource dataSource;
#Autowired
private PlatformTransactionManager transactionManager;
#Bean(name = "batchDatasource")
#ConfigurationProperties(prefix="spring.batchdatasource")
public DataSource batchDataSource(){
return DataSourceBuilder.create().build();
}
#Bean(name = "primaryDatasource")
#ConfigurationProperties(prefix="spring.datasource")
#Primary
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
#Override
public JobRepository createJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(batchDataSource());
// factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.setTablePrefix("schema1"+ ".BATCH_");
factory.afterPropertiesSet();
return factory.getObject();
}
/* Job and step bean definitions here */
My main class is the one annotated with #EnableBatchProcessing
#SpringBootApplication
#EnableBatchProcessing
public class SpringBatchExample1Application {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
I'm getting this Requested bean is currently in creation: Is there an unresolvable circular reference? when trying to configure two datasources. It works fine when using a single datasource by autowiring(refer the commented out lines of code) instead of creating multiple beans.
Following is the exception snippet:
Error creating bean with name 'springBatchConfig': Unsatisfied dependency expressed through method 'setDataSource' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'batchDatasource': Requested bean is currently in creation: Is there an unresolvable circular reference?
I looked up and found out this occurs when there's a dependency on a bean which is still not created or is being created. I just see it in the createJobRepository method where datasource is being plugged. I still face the error even if I don't have the createJobRepository method.
It seems like the requirement is for the datasource beans to be created before others. I tried using the #Order annotation, but no luck.
EDIT:
I tried the solution from #Mykhailo Skliar's Accepted answer below, and serparated the Datasource beans into a new Configuration class. Though it resolved the initial Unresolveble circular reference issue anymore, it led me to the following error:
Error creating bean with name 'springBatchConfig': Invocation of init method failed; nested exception is org.springframework.batch.core.configuration.BatchConfigurationException: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
Based on this answer, I changed my url property names as follows:
spring.datasource.jdbc-url=
spring.datasource.jdbc-url=
Though it solved the jdbcUrl error, it posed another issue:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Reference to database and/or server name in 'sample-sql-server.schema1.MY_TABLE_NAME' is not supported in this version of SQL Server.
Both my data sources are Azure SQL server instances.
I looked up and found it was not possible to use multiple Azure SQL databases years ago, but based on this answer it should not be the case anymore.
The issue is most probably because of
factory.setDataSource(batchDataSource());
You should use autowired bean here, instead of calling batchDataSource()
I would split SpringBatchConfig in two beans:
#Configuration
public class DataSourceConfig {
#Bean(name = "batchDatasource")
#ConfigurationProperties(prefix="spring.batchdatasource")
public DataSource batchDataSource(){
return DataSourceBuilder.create().build();
}
#Bean(name = "primaryDatasource")
#ConfigurationProperties(prefix="spring.datasource")
#Primary
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
}
#Configuration
public class SpringBatchConfig extends DefaultBatchConfigurer{
#Autowired
private JobBuilderFactory jobs;
#Autowired
private StepBuilderFactory steps;
#Qualifier("batchDataSource")
#Autowired
private DataSource batchDataSource;
#Autowired
private PlatformTransactionManager transactionManager;
#Override
public JobRepository createJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(batchDataSource);
factory.setTransactionManager(transactionManager);
factory.setTablePrefix("schema1"+ ".BATCH_");
factory.afterPropertiesSet();
return factory.getObject();
}
}

AutoConfigureTestDatabase with multiple DataSource beans

I have two DataSources in my application, which work as expected when connecting to the databases in a live environment. However, when writing unit tests for this application, I'm encountering problems with my bean definitions.
This is my primary DataSource configuration:
#Configuration
#EnableJpaRepositories(
basePackages = "foo.bar.repository.primary",
entityManagerFactoryRef = "primaryEntityManager",
transactionManagerRef = "primaryTransactionManager")
public class PrimaryDataSourceConfig {
#Bean
#Primary
#ConfigurationProperties("primary.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean primaryEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(primaryDataSource());
em.setPackagesToScan("foo.bar.domain.entity");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Map<String, String> properties = new HashMap<>();
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
em.setJpaPropertyMap(properties);
return em;
}
#Bean
#Primary
public PlatformTransactionManager primaryTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(primaryEntityManager().getObject());
return transactionManager;
}
}
I have a test where all I want to do is spin up the entire application context, looking like this.
#AutoConfigureTestDatabase
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ErpApplicationTest {
#Test
public void test() {
// Application started
}
}
However, when I run this test, I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'primaryEntityManager' defined in class path resource [foo/bar/primaryDataSourceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'primaryEntityManager' threw exception; nested exception is java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
What is causing this error, and what can I do to rectify it? Flyway is able to connect to the embedded H2 instance the annotation generates and run its migrations, but the primary DataSource, alongside its EntityManager fail at creation.
I resolved the issue by doing the following:
First I changed the AutoConfigureTestDatabase-annotation to not replace any DataSource:
#AutoConfigureTestDatabase(
replace = AutoConfigureTestDatabase.Replace.NONE)
I was now experiencing an error where I would timeout against the database. Since the AutoConfig defaults to an in-memory h2, I figured the previous database connection settings were incorrect. I changed my application.properties-file to contain the following:
primary.datasource.driver-class-name=org.h2.Driver
primary.datasource.jdbc-url=jdbc:h2:~;MODE=MYSQL
primary.datasource.username=
primary.datasource.password=
secondary.datasource.driver-class-name=org.h2.Driver
secondary.datasource.jdbc-url=jdbc:h2:~;MODE=MYSQL
secondary.datasource.username=
secondary.datasource.password=
Presumably this error occurred because the auto configuration couldn't properly replace the entityManager for my custom datasource. By ensuring the DataSource wasn't replaced, and ensuring the connection url was correct, the test went through as expected.

EntityManagerFactory Bean in Spring-boot test

I am new to the programming world so what I say may seem silly.
I am trying to run a spring-boot test as JUnit under Eclipse but I just can't figure out how to use the spring-boot annotations... I have read several guides and browsed this website but didn't find anything that resolved my problem.
I am trying to run the JUnit test-class below :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={CBusiness.class,CService.class,CDao.class}, loader = AnnotationConfigContextLoader.class)
#SpringBootTest
public class CalculTest {
#Autowired
CBusiness business;
#Test
public void testCalcul() throws TechnicalException {
Object object= new Object();
object.setId1("00");
object.setId2("01");
object.setNombrePlacesMaximum(new BigInteger("50"));
Long result=business.calcul(object);
assertTrue(result>0);
}
Running this as a JUnit test gives me the following exception :
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
The EntityManager parameter from the CDao class has the annotation #PersistenceContext, I thought this meant it was automatically generated by Hibernate but apparently it isn't... How can I instanciate the EntityManager using only java code? I don't have any .xml or .properties file...
FYI here are the classes called by the test :
Business Layer :
#Component("cBusiness")
public class CBusiness {
#Autowired
CService cService;
public long calcul(Object object) throws TechnicalException {
//Code (calls a method from CService class)
}
Service layer :
#Service
public class CService {
#Autowired
CDao cDao;
Dao Layer
#Repository
#Transactional(rollbackFor = {TechnicalException.class})
public class CDao {
#PersistenceContext
EntityManager entityManager;
I tried testing the method inside a webservice using only the #autowire annotation on the Business layer and if worked fine, however I just cannot instanciate it in the JUnit tests. I tried several ways of running this test and I am not sure this is the right way of doing it, so I'm open to any suggestion.
Thanks in advance.
#Configuration
#EnableTransactionManagement
public class PersistenceJPAConfig{
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "\\your package here" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("\\Driver");
dataSource.setUrl("\\URL");
dataSource.setUsername( "\\userName" );
dataSource.setPassword( "\\password" );
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}

Hibernate SessionFactory annotation based configuration

My recent goal is to build a spring boot application, but without any XML config files (or as less as possible) so I would like to avoid using some XML files (i.e. web.xml) especially for some bean definition parts.
And here comes tougher part.
I want to inject using #Autowired annotation a SessionFactory bean into classes, but everytime I try to start application I get:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'temperatureController': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: EntityManagerFactory must not be null
Ok, I understand that Spring has no SessionFactory bean because it has no EntityManagerFactory.
So I would appreciate any suggestions how to solve this, but only with configuration by annotations.
So far I read similar post to mine about specifying in #Configuration class a bean this way:
#Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
And then adding this line into properties file:
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
And finally #Autowired with SessionFactory should work good.
But, of course for me it's not working.
Any ideas what should I do different/better?
My properties file is very basic:
spring.jpa.show-sql = true
spring.datasource.password=mysql
spring.datasource.username=mysql
spring.datasource.testWhileIdle = true
spring.jpa.hibernate.ddl-auto = update
spring.datasource.validationQuery = SELECT 1
spring.datasource.url= jdbc:mysql://localhost:3306/sys
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
Usually when I want to define something simple I make a class that is similar to the following:
#Configuration
#EnableTransactionManagement
public class PersistanceJpaConfig {
#Bean
public LocalSessionFactoryBean hibernateSessionFactory(DataSource dataSource) {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan(new String[] {
"my.entities.package"
});
sessionFactory.setHibernateProperties(additionalProperties());
return sessionFactory;
}
#Bean HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306");
dataSource.setUsername("user");
dataSource.setPassword("password");
return dataSource;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL57InnoDBDialect");
return properties;
}
}
By using #EnableTransactionManagement and creating a bean of type LocalSessionFactoryBean, spring will automatically create a SessionFactory bean for you that you can inject/autowire anywhere.
Of course you can inject some of the configuration from properties files if needed.

Is PersistenceAnnotationBeanPostProcessor affect somehow on Environment or #PropertySource?

Hi i am beginner in Spring and Jpa Integration. While i have tried to configure my database connection,details handler itp. I came across a strange behavior of spring.
First of all, I have 3 config file:
1) RootConfig - contains everything but controllers
2) WebConfig - contains every Bean which is controllers annotated
3) JdbcConfig - contains Beans related with dataSource, this config is imported by RootConfig using this annotation (#Import(JdbcConfig.class)).
RootConfig looks like this:
#Configuration
#Import(JdbcConfig.class)
#ComponentScan(basePackages = "app", excludeFilters = {#ComponentScan.Filter(type = FilterType.ANNOTATION,value = {EnableWebMvc.class, Controller.class})})
public class RootConfig
{
}
JdbcConfig:
#Configuration
#PropertySource("classpath:db.properties")
#EnableTransactionManagement
public class JdbcConfig
{
#Resource
public Environment env;
#Bean
public DataSource dataSource()
{
System.out.println(env);
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(env.getProperty("dataSource.driverClassName"));
ds.setUrl(env.getProperty("dataSource.Url"));
ds.setUsername(env.getProperty("dataSource.username"));
ds.setPassword(env.getProperty("dataSource.password"));
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource ds, JpaVendorAdapter jpaVendorAdapter)
{
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(ds);
emfb.setJpaVendorAdapter(jpaVendorAdapter);
emfb.setPackagesToScan("app.model");
return emfb;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter()
{
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.POSTGRESQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
adapter.setDatabasePlatform(env.getProperty("dataSource.dialect"));
return adapter;
}
#Bean
public BeanPostProcessor beanPostProcessor()
{
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public JpaTransactionManager jpaTransactionManager(EntityManagerFactory em) {
return new JpaTransactionManager(em)}}
At this moment everything works fine, Environment field is not null value and contains all defined properties. The problem appear when I am trying to add Bean PersistenceAnnotationBeanPostProcessor So when I add this Bean to JdbcConfig.class, Environment field became null but when i add this RootConfig Environment again contains all needed values. So is there any known problem with propertySource and this bean? Is PersistenceAnnotationBeanPostProcessor somehow affect on #PropertySource or #Autorwired(#Inject/#Ressource) Environment field? Is there any reason why Environment must be configure in main config and it cannot be imported from other config by #Import?
I think your problem is related with this spring issue SPR-8269.
Can you try setting up PersistenceAnnotationBeanPostProcessor bean definition as static?
I also had same problem and I solved in this way.

Categories

Resources