RESTful webservice using Java Streams and Spring Boot - java

I try to implement a RESTful WebService that is able to stream millions of records directly from database.
I'm using SpringBoot 2.2.5, Hibernate 5 and PostgreSQL 11
According to this post:
https://www.airpair.com/java/posts/spring-streams-memory-efficiency
one step is needed to set the flag "allowResultAccessAfterCompletion" to true.
But how can I do this in Spring Boot?
So far I do not have any SessionFactory, EntityManagerFactory, Datasource, ... configuration in my application. Everything is autoconfigured by SpringBoot.
If I add the proposed configuration below, the application won't start because of missing SessionFactory.
#Configuration
#EnableTransactionManagement
public class DataConfig {
#Autowired #Bean
public PlatformTransactionManager txManager(SessionFactory sf) {
HibernateTransactionManager mgr = new HibernateTransactionManager(sf);
mgr.setAllowResultAccessAfterCompletion(true);
return mgr;
}
... (the rest of your data config, including the LocalSessionFactoryBean) ...
}
If I provide a SessionFactory bean by unwrapping it from EntityManagerFactory, I get another exception:
Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'getSessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?
Does anyone have a working configuration for my setup?
Can't this flag simply be set by some configuration value in application.properties?
Thank you!

First of all you need to decide whether you need to use Hibernate or Spring JPA for your project. Work with the framework and not against it. Using jpa classes are preferred over hibernate classes by most people today.
Since you are using springboot , the best approach is to work with the framework and use spring-boot-starter-data-jpa which will automatically configure all your necessary beans at startup. In that case, you could provide your own custom beans to override parameters as you want.
In the sample code that you provided in the question, you are using Hibernate classes directly , so you will have to manually create all the necessary beans as spring won't work with you for that unless you disable the auto-configurations which might be causing the circular dependency issue for you.
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.sample.spring.repository")
#PropertySource("classpath:database.properties")
public class DataConfig {
private final String PROPERTY_DRIVER = "driver";
private final String PROPERTY_URL = "url";
private final String PROPERTY_USERNAME = "user";
private final String PROPERTY_PASSWORD = "password";
private final String PROPERTY_SHOW_SQL = "hibernate.show_sql";
private final String PROPERTY_DIALECT = "hibernate.dialect";
#Autowired
Environment environment;
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean lfb = new LocalContainerEntityManagerFactoryBean();
lfb.setDataSource(dataSource());
lfb.setPersistenceProviderClass(HibernatePersistence.class);
lfb.setPackagesToScan("com.sample.spring");
lfb.setJpaProperties(hibernateProps());
return lfb;
}
#Bean
DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setUrl(environment.getProperty(PROPERTY_URL));
ds.setUsername(environment.getProperty(PROPERTY_USERNAME));
ds.setPassword(environment.getProperty(PROPERTY_PASSWORD));
ds.setDriverClassName(environment.getProperty(PROPERTY_DRIVER));
return ds;
}
Properties hibernateProps() {
Properties properties = new Properties();
properties.setProperty(PROPERTY_DIALECT, environment.getProperty(PROPERTY_DIALECT));
properties.setProperty(PROPERTY_SHOW_SQL, environment.getProperty(PROPERTY_SHOW_SQL));
return properties;
}
#Bean
JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
}

You can very well provide your own the SessionFactory as well in which case spring boot will not create another one for you. Following is excerpt from Bootstrapping Hibernate 5 with Spring article, feel free to tweak it as per your needs
#Configuration
#EnableTransactionManagement
public class HibernateConf {
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(
{"com.baeldung.hibernate.bootstrap.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setAllowResultAccessAfterCompletion(true);
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return hibernateProperties;
}
}
Another approach is to use BeanPostProcessor if you know that spring boot is already creating a HibernateTransactionManager in it's own lifecycle. Following is what the outline of the this BeanPostProcessor would look like
public class HTMPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof HibernateTransactionManager) {
((HibernateTransactionManager)bean).setAllowResultAccessAfterCompletion(true);
}
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
return bean; // you can return any other object as well
}
}
Hope this helps!!

Related

Spring Transactional doesn't persist an entity using EntityManager but does using Spring Data

Maybe it is kind of too common but still.
I have a small test project where I'm testing all the JPA stuff. Almost everywhere I'm using Spring Data and JPA repositories work just fine. But now I'm trying to make my service to save entities. The service looks something like this:
#Service
public class SomeServiceImpl implements SomeService {
#Autowired
private EntityManagerFactory entityManagerFactory;
public SomeServiceImpl(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
#Override
#Transactional
public SomeEntity save(SomeEntity someEntity) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.persist(someEntity);
return someEntity;
}
The persistence config looks like this (I'm intentionally copying and pasting the whole config. Maybe it would help you to reproduce the error):
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories
#PropertySource({"classpath:conf/application.properties"})
public class PersistenceConfig {
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() throws SQLException {
PoolDataSourceImpl dataSource = new PoolDataSourceImpl();
dataSource.setConnectionFactoryClassName(environment.getRequiredProperty("db.driverClassName"));
dataSource.setURL(environment.getRequiredProperty("db.url"));
dataSource.setUser(environment.getRequiredProperty("db.username"));
dataSource.setPassword(environment.getRequiredProperty("db.password"));
dataSource.setFastConnectionFailoverEnabled(
Boolean.valueOf(environment.getRequiredProperty("db.fast.connect.failover.enabled")));
dataSource.setValidateConnectionOnBorrow(true);
dataSource.setSQLForValidateConnection("SELECT SYSDATE FROM DUAL");
dataSource.setONSConfiguration(environment.getRequiredProperty("db.ons.config"));
dataSource.setInitialPoolSize(Integer.valueOf(environment.getRequiredProperty("db.initial.pool.size")));
dataSource.setMinPoolSize(Integer.valueOf(environment.getRequiredProperty("db.min.pool.size")));
dataSource.setMaxPoolSize(Integer.valueOf(environment.getRequiredProperty("db.max.pool.size")));
dataSource.setAbandonedConnectionTimeout(0);
dataSource.setInactiveConnectionTimeout(60 * 25);
dataSource.setTimeToLiveConnectionTimeout(0);
dataSource.setMaxConnectionReuseTime(60 * 30L);
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.setProperty("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.setProperty("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.setProperty("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(#Autowired DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setPackagesToScan("com.dropbinc.learning.jpa.model");
JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
Map jpaProperties = new HashMap();
jpaProperties.put("javax.persistence.schema-generation.database.action", "drop-and-create");
entityManagerFactory.setJpaPropertyMap(jpaProperties);
entityManagerFactory.setJpaProperties(hibernateProperties());
return entityManagerFactory;
}
#Bean
public PlatformTransactionManager transactionManager(#Autowired EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
And one more where I'm planning to configurate the rest of the application (placed in the same package):
#Configuration
#ComponentScan(basePackages = "com.dropbinc.learning.jpa")
public class AppConfig {
}
I've tried to debug Spring but all that I wasn't able to detect a difference between transaction behaviour of JPA repositories and my service. I saw transaction was created and even commited. But in case of JPA repositories it got saved while in my service implementation it did generated ids but an entity didn't appeared in a database.
I'm running all the stuff in tests, autowiring the service by interface:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { AppConfig.class, PersistenceConfig.class })
public class AllTheTests {
#Autowired
SomeService someService;
...
}
Thank you very much for any suggestion!
EDIT Adding entityManager.flush() call generates nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress.

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.

Spring Configuration creating two beans instead of one

I'm writing a RESTful web service using Spring MVC, using Java Configuration. My configuration file is below. My issue is this -- I discovered that 2 instances of "myService" bean is being created, instead of just one instance. I'm not sure why? How can I adjust the configuration to create only one?
Can anyone point me in the right direction? Thanks!
Here's my configuration class....
#Configuration
public class MyConfig {
#Bean(name = "dataSource")
public DriverManagerDataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// datasource set up
return dataSource;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DriverManagerDataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.scanPackages("com.mypackages");
sessionBuilder.addProperties(getHibernateProperties());
return sessionBuilder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.enable_lazy_load_no_trans", "true");
properties.put("hibernate.id.new_generator_mappings", "true");
return properties;
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Bean
public MyMainBean MyMainBean() {
MyMainBean bean = new MyMainBean();
bean.setService(myService());
bean.setValidator(myValidator());
return bean;
}
#Bean(name = "myService")
public MyService myService() {
MyService s = new MyService();
s.setDao1(myDao1());
s.setDao2(myDao2());
s.setCopyUtil(copyUtil());
return s;
}
#Bean
public MyDao1 myDao1() {
return new MyDao1();
}
#Bean
public MyDao2 myDao2() {
return new MyDao2();
}
#Bean
public CopyUtil copyUtil() {
return new CopyUtil();
}
#Bean
public ReportValidator reportValidator() {
ReportValidator validator = new ReportValidator();
validator.setService(myService());
return validator;
}
#Bean
public XMLValidator xmlValidator() {
XMLValidator validator = new XMLValidator();
validator.setService(myService());
return validator;
}
}
Actually, Spring is smart when wiring beans and should only call the myService() function once, and then pass the result to the other myService() calls, resulting in only one bean of MyService.
Make sure you really are getting 2 instances of MyService, e.g. by adding a log in the constructor of the MyService class.
If you truly see more than one constructor log statement, make sure that you are not declaring other MyService beans in other #Configuration classes, or that you are not using any component annotation on the MyService class (i.e. don't use #Service, #Component, #Repository).
If you declare the class with #Service, it effectively instantiates the class and adds it to the context. When you declare it again with #Bean you end up with 2 instances, so don't mix them.
Also, you don't need to use those #Autowired annotations here, or even calls to other beans, because the following will also work:
#Configuration
public class DbConfiguration {
#Bean
public MovieDao dao() {
return new MovieDao();
}
#Bean
public MovieService service(MovieDao dao) {
return new MovieService(dao);
}
}
Spring will see that you need a MovieDao to build a MovieService and it will instantiate the dao first and pass it to the service bean. You don't even need to add #Service or similar annotations to your classes!
It really is that good, hope these tips help ;)

How to verify Spring + AspecJ Transactions?

I'm pretty sure transactions are not being applied in my Spring Boot application, even though I am using #EnableTransactionManagement(mode=AdviceMode.ASPECTJ) & have spring-aspects in my app.
Configuration
#Configuration
public class DatastoreConfig{
#Bean
public DataSource dataSource(){ ///... }
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
#Bean
public String databaseSchema(){
return "mySchema";
}
#Bean
public OpenSessionInViewInterceptor openSessionInViewInterceptor(SessionFactory sessionFactory){
OpenSessionInViewInterceptor result = new OpenSessionInViewInterceptor();
result.setSessionFactory(sessionFactory);
return result;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter vendorAdapter){
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan( Main.class.getPackage().getName() + ".model");
factory.setDataSource(dataSource);
factory.setJpaProperties(getJpaProperties());
factory.afterPropertiesSet();
return factory;
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter(){
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setDatabasePlatform(PostgreSQL9Dialect.class.getName());
return vendorAdapter;
}
#Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory emf){
SessionFactoryImpl sf = (SessionFactoryImpl) emf.getSessionFactory();
return sf;
}
private Properties getJpaProperties() {
Properties props = new Properties();
// props.put("hibernate.hbm2ddl.auto", "validate");
props.put("hibernate.ejb.naming_strategy", ImprovedNamingStrategy.class.getName());
props.put("hibernate.enable_lazy_load_no_trans", "true");
props.put("jadira.usertype.autoRegisterUserTypes", "true");
return props;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory emf) throws PropertyVetoException {
JpaTransactionManager transactionManager = new JpaTransactionManager(emf);
transactionManager.setRollbackOnCommitFailure(true);
transactionManager.setDataSource(dataSource());
return transactionManager;
}
#Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
Main class
#Configuration
#EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
#ComponentScan
#EnableAsync
#EnableScheduling
#EnableEntityLinks
#EnableAspectJAutoProxy
#EnableApiResources(apiPrefix = "")
#EnableJpaRepositories(transactionManagerRef = "transactionManager")
#EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
#EnableConfigurationProperties
#EnableAutoConfiguration
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
#EnableWebSocketMessageBroker
#Slf4j
public class Main extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Main.class);
}
public static void main(String[] args) {
Object[] sources = {
Main.class,
TomcatConfig.class // include for embedded tomcat...
};
ConfigurableApplicationContext result = SpringApplication.run(sources, args);
}
}
Attempt to verify
One of the ways I was trying to verify was by running
#Component
public class SomeService{
#Transactional
#Override
protected void tryItOut(){
// this is always false
boolean declarativeTransaction = TransactionSynchronizationManager.isActualTransactionActive();
// this throws an exception
TransactionStatus aspect = TransactionAspectSupport.currentTransactionStatus();
}
}
However, if I insert a call to transactionManager.getTransaction(new DefaultTransactionDefinition()); beforehand, declarativeTransaction is true.
Any advice on how to set up #Transactions / verify they're working?
Your configuration is contradicting itself.
#EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
Means you are using loadtime or compile time weaving of the aspects. Judging on your configuration you aren't using that. If I have to judge your configuration you are just using basic proxies no weaving.Just remove AdviceMode.ASPECTJ and it will work, you also don't need the #EnableAspectJAutoProxy as applying transactions has nothing to do with that it (it can work without it).
Also your configuration is doing a lot to basically not use Spring Boot. You have configured a lot of things that spring boot already does for you automatically, manually.
Spring Boot already configures the following for you (just by only specifying #EnableAutoConfiguration.
EntityManagerFactory
DataSource
JdbcTemplate
Transaction Setup
OpenEntityManagerInView
Spring Web Sockets
Hypermedia support
Spring Data JPA setup
You can remove a whole lot of your configuration and put some properties in application.properties.
If you really need the SessionFactory instead of doing the casting yourself I strongly suggest the use of the HibernateJpaSessionFactoryBean.
I would suspect the following main class to still work (with transaction enabled).
#Configuration
#ComponentScan
#EnableAsync
#EnableScheduling
#EnableAutoConfiguration
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
#EnableWebSocketMessageBroker
#Slf4j
public class Main extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Main.class);
}
public static void main(String[] args) {
Object[] sources = {
Main.class,
TomcatConfig.class // include for embedded tomcat...
};
ConfigurableApplicationContext result = SpringApplication.run(sources, args);
}
}
With this DatastoreConfig class
#Configuration
public class DatastoreConfig{
#Bean
public FactoryBean<SessionFactory> sessionFactory(EntityManagerFactory emf){
HibernateJpaSessionFactoryBean jpaSessionFactoryBean = new HibernateJpaSessionFactoryBean();
jpaSessionFactoryBean.setEntityManagerFactory(emf);
return jpaSessionFactoryBean;
}
}
And this application.properties
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
You probably need to add some spring.datasource. properties to setup your datasource correctly. Also judging from the fact that you had a OpenSessionInViewInterceptor you used that instead of the OpenEntityManagerInViewInterceptor (or filter). So you might even be able to remove that.
Not sure if that is al your configuration but you might be able to remove/trim down even more. I suggest a look at the Spring Boot reference guide to get a feeling for what is already automatically configured.

#Autowired bean not being found

I'm getting errors trying to inject resource dependencies into my unit testing.
My approach has been to write a TestConfig.java to replace the applicationContext.xml for production which manages the connections of the beans. So that I can run it with an in-memory database and just test components.
TestConfig.java
#Configuration
#EnableTransactionManagement
public class TestConfig {
#Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.hsqldb.jdbcDriver");
ds.setUrl("jdbc:hsqldb:mem:testdb");
ds.setUsername("sa");
ds.setPassword("");
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
LocalContainerEntityManagerFactoryBean lcemfb
= new LocalContainerEntityManagerFactoryBean();
lcemfb.setDataSource(this.dataSource());
lcemfb.setPackagesToScan(new String[] {"com.dao","com.data"});
lcemfb.setPersistenceUnitName("MyTestPU");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
lcemfb.setJpaVendorAdapter(va);
Properties ps = new Properties();
ps.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
ps.put("hibernate.hbm2ddl.auto", "create");
lcemfb.setJpaProperties(ps);
lcemfb.afterPropertiesSet();
return lcemfb;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(this.entityManagerFactoryBean().getObject());
return tm;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor()
{
return new AutowiredAnnotationBeanPostProcessor();
}
}
ProductsDaoTest.java
#ContextConfiguration(classes = { TestConfig.class })
#RunWith(SpringJUnit4ClassRunner.class)
public class ProductsDaoTest {
#Resource(name="com.dao.ProductsDao")
private ProductsDao testDao;
#Test
public void testSaveProduct() {
Product productA = new Product();
testDao.save(productA);
Set<Product> products = testDao.getAllProducts();
assertNotNull(products);
}
}
The error is Error creating bean with name 'com.dao.ProductsDaoTest': Injection of resource dependencies failed
So it can't find the ProductDao Bean which is a #Repository with a #Autowired sessionFactory.
So my guess is that because I'm not naming the beans using xml it can't find it, though I thought it should automatically pick it up from setPackagesToScan(). So is there a way to manually insert the Bean mapping so that it can be found?
Also more generally is this a reasonable way to go about testing Spring DAO configurations?
Regards,
Iain
I think you are trying to use wrong name of your DAO bean in #Resource annotation. Have you explicitly specify name of the ProductsDao bean using #Qualifier? If no, then as I remember by default the name of the bean will be productsDao. So you should inject your DAO like:
#Resource(name="productsDao")
private ProductsDao testDao;
If you have only one ProductDAO implementation then simply write:
#Autowired
private ProductsDao testDao;
or
#Inject
private ProductsDao testDao;
In case if you want to give specific name to DAO then use next construction:
#Respository
#Qualifier(name="specificName")
public class ProductDAO...
EDIT:
As Boris noted you should also specify which package to scan for defined beans (classes annotated with #Component, #Service, #Repository...). For this you should add #ComponentScan annotation to your configuration class definition.
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = {"package_to_scan"})
public class TestConfig {...}

Categories

Resources