How does a bean, with #Autowired, gets its dependency if the dependency's interface does not exist in the container - spring

I am learning Spring framework and I am stuck now about dependency injection.
In this question, I am asking about Java Configuration.
I know #Autowired annotation automatically wires the dependency and the bean by referencing a qualified implementation class of the declared interface.
However, I do not know how the function, transactionManager(SessionFactory sessionFactory), gets its SessionFactory argument instance when there is no bean returns SessionFactory in my studying code.
#Bean
public LocalSessionFactoryBean sessionFactory(){
// create session factorys
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
// set the properties
sessionFactory.setDataSource(securityDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hiberante.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
I assume that the transactionManager() gets its argument from sessionFactory(). But sessionFactory() does not return SessionFactory instance, it returns LocalSessionFactoryBean. The LocalSessionFactoryBean does not implement SessionFactory either, it implements FactoryBean<SessionFactory>.
In this case, doesn't transactionManager() suppose to use argument type LocalSessionFactoryBean or FactoryBean<SessionFactory> instead of having SessionFactory? Like: transactionManager(FactoryBean<SessionFactory> sessionFactory)
I am confused with how transactionManager() gets its dependency.
Thank you,

If am understanding it right you are telling spring to create session factory for you using the configurations provided via LocalSessionFactoryBean, see details here, it creates hibernate session factory for you and auto wire it. Actually its Spring frameworks common practice to save developer work here by letting you create session factory with minimum code.

Related

Need to configure my JPA layer to use a TransactionManager (Spring Cloud Task + Batch register a PlatformTransactionManager unexpectedly)

I am using Spring Cloud Task + Batch in a project.
I plan to use different datasources for business data and Spring audit data on the task. So I configured something like:
#Bean
public TaskConfigurer taskConfigurer() {
return new DefaultTaskConfigurer(this.singletonNotExposedSpringDatasource());
}
#Bean
public BatchConfigurer batchConfigurer() {
return new DefaultBatchConfigurer(this.singletonNotExposedSpringDatasource());
}
whereas main datasource is autoconfigured through JpaBaseConfiguration.
The problem comes when SimpleBatchConfiguration+DefaultBatchConfigurer expose a PlatformTransactionManager bean, since JpaBaseConfiguration has a #ConditionalOnMissingBean on PlatformTransactionManager. Therefore Batch's PlatformTransactionManager, binded to the spring.datasource takes place.
So far, this seems to be caused because this bug
So I tried to emulate what JpaBaseConfiguration does, defining my own PlatformTransactionManager over my biz datasource/entityManager.
#Primary
#Bean
public PlatformTransactionManager appTransactionManager(final LocalContainerEntityManagerFactoryBean appEntityManager) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(appEntityManager.getObject());
this.appTransactionManager = transactionManager;
return transactionManager;
}
Note I have to define it with a name other than transactionManager, otherwise Spring finds 2 beans and complains (unregardless of #Primary!)
But now it comes the funny part. When running the tests, everything runs smooth, tests finish and DDLs are properly created for both business and Batch/Task's databases, database reads work flawlessly, but business data is not persisted in my testing database, so final assertThats fail when counting. If I #Autowire in my test PlatformTransactionManager or ÈntityManager, everything indicates they are the proper ones. But if I debug within entityRepository.save, and execute org.springframework.transaction.interceptor.TransactionAspectSupport.currentTransactionStatus(), it seems the DatasourceTransactionManager from Batch's configuration is overriding, so my custom exposed PlatformTransactionManager is not being used.
So I guess it is not a problem of my PlatformManager being the primary, but that something is configuring my JPA layer TransactionInterceptor to use the non primary but transactionManager named bean of Batch.
I also tried with making my #Configuration implement TransactionManagementConfigurer and override PlatformTransactionManager annotationDrivenTransactionManager() but still no luck
Thus, I guess what I am asking is whether there is a way to configure the primary TransactionManager for the JPA Layer.
The problem comes when SimpleBatchConfiguration+DefaultBatchConfigurer expose a PlatformTransactionManager bean,
As you mentioned, this is indeed what was reported in BATCH-2788. The solution we are exploring is to expose the transaction manager bean only if Spring Batch creates it.
In the meantime you can set the property spring.main.allow-bean-definition-overriding=true to allow bean definition overriding and set the transaction manager you want Spring Batch to use with BatchConfigurer#getTransactionManager. In your case, it would be something like:
#Bean
public BatchConfigurer batchConfigurer() {
return new DefaultBatchConfigurer(this.singletonNotExposedSpringDatasource()) {
#Override
public PlatformTransactionManager getTransactionManager() {
return new MyTransactionManager();
}
};
}
Hope this helps.

Using ObjectDB with Spring Data JPA "com.objectdb.jpa.EMF is not an interface"

Overflowers
I'm trying to get ObjectDB (2.7.6_01, latest) with Spring Data JPA (2.1.4, seemingly latest).
The docs for Spring Data JPA say that a version 2.1 JPA provider is needed. AFAIKT ObjectDB's JPA provider is 2.0 ... not sure if this is the problem or not.
But my problem is this exception:
Caused by: java.lang.IllegalArgumentException: com.objectdb.jpa.EMF is not an interface
Which is causing:
EntityManagerFactory interface [class com.objectdb.jpa.EMF] seems to conflict with Spring's EntityManagerFactoryInfo mixin - consider resetting the 'entityManagerFactoryInterface' property to plain [javax.persistence.EntityManagerFactory]
I'm happy that the ObjectDB entity manager factory is being picked properly by my code, but Spring's CGLIB wrapper around this class (EMF) is not working out.
Anyone got any ideas?
Gradle dependencies:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compile files('libs/objectdb-jee.jar')
compileOnly 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
Then, either of these two #Beans (one or the other, not both) cause the same EMF exception above:
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
final ObjectdbJpaVendorAdapter vendorAdapter = new ObjectdbJpaVendorAdapter();
return vendorAdapter;
}
Or
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final ObjectdbJpaVendorAdapter vendorAdapter = new ObjectdbJpaVendorAdapter();
vendorAdapter.setShowSql(true);
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.example.demo.persistence");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory;
}
I've got a no-op DataSource #Bean to keep some facet of Spring happy, but I don't think it's playing an active role in this problem.
No spring.jpa.* set at all.
Cheers
The Beans that you have to provide are much more simple:
#Bean
#ConfigurationProperties("app.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name="entityManagerFactory")
public EntityManagerFactory getEntityManagerFactoryBean() {
// this is the important part - here we use a local objectdb file
// but you can provide connection string to a remote objectdb server
// in the same way you create objectdb EntityManagerFactory not in Spring
return Persistence.createEntityManagerFactory("spring-data-jpa-test.odb");
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
With the above (and the proper dependencies in your pom.xml) there is no need for any additional configuration (i.e. no need for any configuration in application.properties).
A simple working example can be found here.

Why adding #Bean to a method I'll call directly

I have seen lots of examples about Spring configuration through #Configuration and #Bean annotations. But I relealized that it's a common practice to add #Bean annotation to methods that are called directly to populate other beans. For example:
#Bean
public Properties hibernateProperties() {
Properties hibernateProp = new Properties();
hibernateProp.put("hibernate.dialect",
"org.hibernate.dialect.H2Dialect");
hibernateProp.put("hibernate.hbm2ddl.auto", "create-drop");
hibernateProp.put("hibernate.format_sql", true);
hibernateProp.put("hibernate.use_sql_comments", true);
hibernateProp.put("hibernate.show_sql", true);
return hibernateProp;
}
#Bean public SessionFactory sessionFactory() {
return new LocalSessionFactoryBuilder(dataSource())
.scanPackages("com.ps.ents")
.addProperties(hibernateProperties())
.buildSessionFactory();}
So, I'm wondering if it's better just declaring the hibernateProperties() as private without the #Bean annotation.
I would like to know if this is a bad/unneeded common practice or there is a reason behind.
Thanks in advance!
According to Spring Documentation inter-bean dependency injection is one good approach in order to define the bean dependencies in a simple form. Of course if you define your hibernateProperties() as private it will work but it could not be injected to other components in your application through Spring Container.
Just decide depending on how many classes depends on your bean and also if you need to reuse it in order to call its methods or inject it to other classes.
Decorating a method in #Configuration class with #Bean means that the return value of that method will become a Spring bean.
By default those beans are singletons(only one instance for the lifespan of the application).
In your example Spring knows that hibernateProperties() is a singleton bean and will create it only ones. So here:
#Bean public SessionFactory sessionFactory() {
return new LocalSessionFactoryBuilder(dataSource())
.scanPackages("com.ps.ents")
.addProperties(hibernateProperties())
.buildSessionFactory();
}
hibernateProperties() method will not be executed again, but the bean will be taken from the application context. If you don't annotate hibernateProperties() with #Bean it will be a simple java method and it will be executed whenever it's called. It depends on what you want.
Just to mention, the other way to do dependency injection in #Configuration classes is add a parameter. Like this:
#Bean public SessionFactory sessionFactory(Properties props) {
return new LocalSessionFactoryBuilder(dataSource())
.scanPackages("com.ps.ents")
.addProperties(props)
.buildSessionFactory();
}
When Spring tries to create the sessionFactory() bean it will first look in the application context for a bean of type Properties.

Is there a way to define a default transaction manager in Spring

I have an existing application that uses the Hibernate SessionFactory for one database. We are adding another database for doing analytics. The transactions will never cross so I don't need JTA, but I do want to use JPA EntityManager for the new database.
I've set up the EntityManager and the new transaction manager, which I've qualified, but Spring complains that I need to qualify my existing #Transactional annotations. I'm trying to find a way to tell Spring to use the txManager one as the default. Is there any way of doing this? Otherwise I'll have to add the qualifier to all the existing #Transactional annotations which I would like to avoid if possible.
#Bean(name = "jpaTx")
public PlatformTransactionManager transactionManagerJPA() throws NamingException {
JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory());
return txManager;
}
#Bean
public PlatformTransactionManager txManager() throws Exception {
HibernateTransactionManager txManager = new HibernateTransactionManager(sessionFactory());
txManager.setNestedTransactionAllowed(true);
return txManager;
}
Error I'm getting
No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2:
Thanks
I was able to solve this using the #Primary annotation
#Bean(name = "jpaTx")
public PlatformTransactionManager transactionManagerJPA() throws NamingException {
JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory());
return txManager;
}
#Bean
#Primary
public PlatformTransactionManager txManager() throws Exception {
HibernateTransactionManager txManager = new HibernateTransactionManager(sessionFactory());
txManager.setNestedTransactionAllowed(true);
return txManager;
}
Since the same type of bean is produced from two methods, you must qualify the #Transactional annotation with the named bean. An easy way around to suite your need will be to use two different Spring application contexts. One operating with the old data source and one operating with new. Each of these contexts will have only one method producing the PlatformTransactionManager instance.

Programmatically create SessionFactory in Spring

Suppose I programmatically create a AnnotationSessionFactoryBean and set the various properties correctly. How can I then extract the Hibernate SessionFactory, since all methods that pertain to creating the SessionFactory are protected?
AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
SessionFactory sessionFactory = sessionFactoryBean.newSessionFactory(); // Protected!!
Use getObject(), after calling afterPropertiesSet():
sessionFactoryBean.afterPropertiesSet();
SessionFactory sessionFactory = sessionFactoryBean.getObject();
(AnnotationSessionFactoryBean implements FactoryBean<SessionFactory>)
Be careful, though: by doing this, it becomes your responsibility to make sure the SessionFactory is closed when you're finished with it.

Resources