Spring and null pointer exception - spring

I'm trying to do this:
#Controller
public class HomeController {
#Autowired
private TemplatesService templatesService;
public final String TEST = templatesService.getUri();
The getUri:
#SuppressWarnings("unchecked")
public String getUri() {
return (String) sessionFactory.getCurrentSession()
.createQuery("select uri from Templates WHERE state=1")
.uniqueResult();
}
It will work correctly, if I'll declare TEST in any method. But now I'm having this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController' defined in file [C:\Users\anton\springsource\vfabric-tc-server-developer-2.8.2.RELEASE\base-instance\wtpwebapps\blog\WEB-INF\classes\net\babobka\blog\controller\HomeController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [net.babobka.blog.controller.HomeController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
My root-context(I don't think it's helpful):
<context:annotation-config />
<context:component-scan base-package="net.babobka.blog" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="template" />
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="headHunter" />
</set>
</property>
</bean>
<bean id="converter" class="net.babobka.blog.headHunter.Converter" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/db/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>/WEB-INF/db/hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">${jdbc.show_sql}</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<mvc:annotation-driven />
<tx:annotation-driven />
<task:annotation-driven />
<bean id="Backupper" class="net.babobka.blog.backupper.Backupper"></bean>
<bean id="OldDataRemoval" class="net.babobka.blog.termination.OldDataRemoval"></bean>
<bean id="HeadHunterImport" class="net.babobka.blog.headHunter.HeadHunterImport"></bean>
<bean id="urlForwardController"
class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
</beans>
What's wrong?

It's not working because templatesService is not yet injected when you reference it to set TEST. Fields injection will only work after the instantiation of your Object. What you need to solve this is use #PostConstruct to set test.
#Controller
public class HomeController {
#Autowired
private TemplatesService templatesService;
public String test;
#PostConstruct
public void init() {
this.test = templatesService.getUri();
}
if you still want to use final, you can use injection by constructor and set TEST then.
#Controller
public class HomeController {
private TemplatesService templatesService;
public final String TEST;
#Autowired
public HomeController(TemplatesService templatesService) {
this.templatesService = templatesService;
this.TEST = templatesService.getUri();
}

This is a problem of initialization order. Spring will inject dependencies into #Autowired fields after it has invoked a bean's constructor, but a field initializer is executed during object construction - and therefore before the field has been autowired. The field is therefore still null, which is why attempting to invoke a method throws a NullPointerException.
Alternatives:
pass the TemplatesService by constructor injection, and assign the final field from the constructor rather than the field initializer
continue to inject the TemplatesService by field injection, but move initialization of the bean into a #PostConstruct method. You will have to remove final to pacify the compiler.
inject the TemplatesService by setter injection, and perform the necessary initialization in the setter. You will have to remove final to pacify the compiler.

Related

Spring 4 + Hibernate 5: No bean named 'transactionManager' is defined

I have a problem with my project when I call a URL.
This is my applicationContext
<context:component-scan base-package="com.prova" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="dataSource"
<!-- connection to datasource -->
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.prova.model"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.id.new_generator_mappings">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager"
name ="transactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
This is my Controller
package com.prova.controller;
<!-- import -->
#Controller
public class EmployeeController {
private static final Logger logger = Logger
.getLogger(EmployeeController.class);
public EmployeeController() {
System.out.println("EmployeeController()");
}
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = "/all")
public ModelAndView listEmployee(ModelAndView model) throws IOException {
List<Employee> listEmployee = employeeService.getAllEmployees();
model.addObject("listEmployee", listEmployee);
model.setViewName("home");
return model;
}
...
...
...
When I call in postman the url http://localhost:8082/prova/all I receive this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'transactionManager' - neither qualifier match nor bean name match!
Please help me because I try all solutions.
Thanks!

spring Multi DataSource #Service annotation with existing error

I have a code that is an error in the Spring Framework
Error Cause I know
So I do not know how to solve it the question.
I am being used with mybatis library
I had multi DataSource of two Account DataBase
I created a root-context.xml
-----------------------root-context.xml -----------------------------------------------------------
Oracle Account 1 Test1
<bean id="dataSourceTest1" class="org.apache.commons.dbcp.BasicDataSource" destroy-m
ethod="close">
<property name="driverClassName" value="net.sf.log4jdbc.DriverSpy"/>
<property name="url" value="jdbc:log4jdbc:oracle:thin:#111.111.1111.1111:1111:Test1"/>
<property name="username" value="TEST1"/>
<property name="password" value="TEST1"/>
<property name="maxIdle" value="200"/>
<property name="maxActive" value="200"/>
<property name="minIdle" value="5"/>
</bean>
<bean id="sqlSessionFactoryTest1" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceTest1" />
<property name="mapperLocations" value="classpath*:test/service/server/test1/**/*.xml" />
</bean>
<bean id="sqlSessionTest1" class="org.mybatis.spring.SqlSessionTemplate" name="sqlSessionTest1">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryTest1" />
</bean>
<mybatis-spring:scan base-package="test.service.server.test1" template-ref="sqlSessionTest1" />
Oracle Account test2
<bean id="dataSourceTest2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="net.sf.log4jdbc.DriverSpy"/>
<property name="url" value="jdbc:log4jdbc:oracle:thin:#222.222.2222.222:2222:Test2"/>
<property name="username" value="Test2"/>
<property name="password" value="Test2"/>
<property name="maxIdle" value="200"/>
<property name="maxActive" value="200"/>
<property name="minIdle" value="5"/>
</bean>
<bean id="sqlSessionFactoryTest2" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceTest2" />
<property name="mapperLocations" value="classpath*:test/service/server/test2/**/*.xml" />
</bean>
<bean id="sqlSessionTest2" class="org.mybatis.spring.SqlSessionTemplate" name="sqlSessionTest2">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryTest2" />
</bean>
<mybatis-spring:scan base-package="test.service.server.test2" template-ref="sqlSessionTest2"/>
-----------------------root-context.xml END ---------------------------------------------------------
i am not used context:component-scan
<!-- <context:component-scan base-package="test.service.server.test1.test1service"/>-->
<!-- <context:component-scan base-package="test.service.server.test2.test2service"/>-->
I use the SpringJUnit4 each unit test
Were sequentially to (DataSourceTest and SqlSessionFactory Test and SqlSession Test mapperScanTest).
did not have any problems until mapperScanTest.
However, an error occurs when star using the annotation # Service
------------------------------------------service interface code ------------------------------------
public interface Test2_SERVICE {
public List<Test2_VO> GET_ListVO();
}
-------------------------------------------implement service code----------------------------------
#Service("Test2_SERVICE") *//<--Error annotaion*
public class Test2_SERVICEIMPLE implements Test2_SERVICE{
#Resource
Test2_MAPPER mapper;
#Override
public List<Test2_VO> GET_ListVO() {
return mapper.GET_ListMapperVO();
}
}
---------test Code------------------------------
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/main/**/*-context.xml" })
public class TestService {
Logger logger = Logger.getLogger(Thread.currentThread().getClass());
#Autowired
#Qualifier("Test2_SERVICE")
Test2_SERVICE test2_SERVICE;
#Override
public void testString() {
logger.info("---------------------");
List<Test2_VO> listVO = test2_SERVICE.GET_ListVO();
logger.info(listVO );
logger.info("---------------------");
}
}
Error Messages-----------------------------------
Caused by:
org.springframework.context.annotation.ConflictingBeanDefinitionException:
Annotation-specified bean name 'Test2_SERVICE' for bean class
[test.service.server.test2.test2service.Test2_SERVICE] conflicts with
existing, non-compatible bean definition of same name and class
[test.service.server.test2.test2service.Test2_SERVICEIMPLE]
------------------------------------------------end---------------------------------------------
#Service("Test2_SERVICE") *//<--Error annotaion*
The problem did not exist until the object Test2_MAPPER
However, the error begins in Test2_SERVICE
# Service ("Test2_SERVICE") Where there is only used here (Test2_SERVICEIMPLE).
Because of this problem
I am suffering for three days..
Somebody tell me solve the problem for this error message.
Thank you for reading my article.
The problem is that you create a bean with the name "Test2_SERVICE" for Test2_SERVICEIMPLE with this annotation:
#Service("Test2_SERVICE")
//creates the bean with id="TEST2_Service" of the type Test2_SERVICEIMPLE
public class Test2_SERVICEIMPLE implements Test2_SERVICE
and then assign exactly this Test2_SERVICEIMPLE bean to the interface Test2Service
#Autowired
#Qualifier("Test2_SERVICE")
//here you assign the bean of the not matching type Test2_SERVICEIMPLE to
//a variable of type Test2_SERVICE
Test2_SERVICE test2_SERVICE;
That means that the interface wants to use the bean for the implementation...
So just remove/change the #Qualifier("Test2_SERVICE") or change the name of the #Service("Test2_SERVICE")
How to autowire annotation qualifiers and how to name autodetected components

No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:

I use Spring and Spring data for the system that I am developing. The following is the config file.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="co.infovilla.vendor" />
<context:component-scan base-package="co.infovilla.vendor.repositories" />
<context:component-scan base-package="co.infovilla.vendor.services" />
<jpa:repositories base-package="co.infovilla.vendor.repositories" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/vendordb" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
</beans>
When I access it using the following code I get exceptions.
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("application-context.xml");
ProductService productService = ctx.getBean(ProductService.class);
Product product = new Product();
product.setName("Phone");
product.setPrice(500000);
productService.save(product);
}
The exceptions are:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at co.infovilla.vendor.main.App.main(App.java:11)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:343)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:442)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303)
... 13 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:538)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:497)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:659)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:632)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:164)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:340)
... 26 more
As far as I know I don't need to configure the entity manager factory when using JPA the way I am using it. What might have gone wrong?
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
This isn't configuring an EntityManagerFactory but a SessionFactory. To configure an EntityManagerFactory use a LocalContainerEntityManagerFactoryBean. See here for more information on how to setup JPA with Spring.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="packagesToScan" value="[package-containing-your-#Entities]"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
</bean>
</property>
</bean>
You probably also want to use the specific MySQL5InnoDBDialect instead of the plain MysqlDialect.

Spring autowire by constructor not working without setter method

Here is my Spring xml config:
<beans profile="test">
<context:annotation-config />
<!-- hsqldbDataSource bean for testing purposes -->
<bean id="hsqldbDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="shutdown">
<constructor-arg>
<bean class="com.zaxxer.hikari.HikariConfig">
<constructor-arg>
<props>
<prop key="dataSource.url">${hsqldb.url}</prop>
<prop key="dataSource.user">${user}</prop>
<prop key="dataSource.password">${password}</prop>
</props>
</constructor-arg>
<property name="dataSourceClassName" value="org.hsqldb.jdbc.JDBCDataSource" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="maximumPoolSize" value="5" />
<property name="minimumPoolSize" value="1" />
</bean>
</constructor-arg>
</bean>
<!-- execute a script to create tables after creation of bean for in-memory HSQLDB -->
<jdbc:embedded-database id="hsqldbDataSource" type="HSQL">
<jdbc:script location="classpath:schema.sql" />
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
<bean id="daoManager" class="com.d.DAOManager" autowire="constructor">
<property name="dataSource" ref="hsqldbDataSource"/>
</bean>
</beans>
And my DAOManager class:
public class DAOManager {
private DataSource dataSource;
private Connection connection;
#Autowired
public DAOManager(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
And here I call get my daoManager bean.
public static DAOManager createHSQLDBDAOManager() {
LOG.info("Setting up datasource to in-memory HSQLDB");
ConfigurableEnvironment env = (ConfigurableEnvironment)applicationContext.getEnvironment();
env.setActiveProfiles("test");
applicationContext.load("classpath:/applicationContext.xml");
applicationContext.refresh();
DAOManager daoManager = applicationContext.getBean("daoManager", DAOManager.class);
return daoManager;
}
Why is it complaining if I remove the setter method? I don't need it. If I remove the #Autowired before the constructor (it also works) it's just useless and not using the by constructor autowire function.
Needed to remove the property value of the daoManager bean
<bean id="daoManager" class="com.d.DAOManager" autowire="constructor"/>

how to get transaction supporting proxy from spring application context?

i need to use bean from spring application context not in a spring managed bean, so i do next: annotate bean with #Service annotation, so instance of bean created during spring loading.
<bean id="customRevisionListener" class="ru.csbi.registry.services.impl.envers.CustomRevisionListener" />
This instance is ApplicationContextAware, so application context is injected in this bean instance and i save it to static variable:
#Service
public class CustomRevisionListener implements EntityTrackingRevisionListener, ApplicationContextAware {
private static ApplicationContext applicationContext;
private ModelInformationService modelInformationService;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CustomRevisionListener.applicationContext = applicationContext;
}
private ModelInformationService getModelInformationService() {
if (modelInformationService == null) {
modelInformationService = applicationContext.getBean(ModelInformationService.class);
}
// TransactionProxyFactoryBean
return modelInformationService;
}
After that another instance of CustomRevisionListener created in not spring context(hibernate envers context). Here i use static variable to receive spring applicationContext
after that i'm getting beans from application context:
private ModelInformationService getModelInformationService() {
if (modelInformationService == null) {
modelInformationService = applicationContext.getBean(ModelInformationService.class);
}
the problem is that this bean has all #Autowired properties injected correctly:
#Service
public class ModelInformationServiceImpl implements ModelInformationService {
#Autowired
private EntityChangeService entityChangeService; // injected correctly
#Autowired
private PropertyService propertyService; // injected correctly
#Autowired
private ru.csbi.registry.services.reflection.HibernateDomainService hibernateService; // injected correctly
, but they are simple instances of java classes not Proxies supporting #Transactional annotation, which they are for my regular spring code:
getModelInformationService().getClass().getName() is "ru.csbi.registry.services.impl.envers.ModelInformationServiceImpl"
and must be something like
$Proxy71
How to get transaction supporting proxies, which spring genereates for example when injecting beans in #Controller, in bean not managed by spring?
i'm using next spring config:
<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg ref="lazyConnectionDataSourceProxy"/>
</bean>
<bean id="lazyConnectionDataSourceProxy" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<property name="targetDataSource">
<ref local="dataSourceTarget" />
</property>
</bean>
<bean id="dataSourceTarget" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${ds.driver}" />
<property name="url" value="${ds.url}" />
<property name="username" value="${ds.user}" />
<property name="password" value="${ds.password}" />
<property name="initialSize" value="${ds.initialSize}" />
<property name="maxActive" value="${ds.maxActive}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!--property name="entityInterceptor">
<bean class="ru.csbi.registry.utils.audit.AuditLogInterceptor">
<property name="sessionFactory" ref="auditSessionFactory" />
</bean>
</property-->
<property name="dataSource" ref="dataSource" />
<property name="lobHandler" ref="oracleLobHandler" />
<property name="packagesToScan" value="ru.csbi.registry.domain" />
<property name="hibernateProperties">
<bean id="hibernatePropertiesFactoryBean" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>file:${realtyregistry.settings.path}/hibernate-config.properties</value>
</list>
</property>
</bean>
</property>
<property name="eventListeners">
<map>
<entry key="post-insert" value-ref="auditEventListener" />
<entry key="post-update" value-ref="auditEventListener" />
<entry key="post-delete" value-ref="auditEventListener" />
<entry key="pre-collection-update" value-ref="auditEventListener" />
<entry key="pre-collection-remove" value-ref="auditEventListener" />
<entry key="post-collection-recreate" value-ref="auditEventListener" />
</map>
</property>
</bean>
<bean id="auditEventListener" class="org.hibernate.envers.event.AuditEventListener" />
<bean id="persistenceManagerHibernate" class="ru.csbi.registry.utils.PersistenceManagerHibernate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

Resources