spring mvc send email (javamail) exception not getting caught - email

I am trying to send an email but before I was getting a nullpointerexception error which was due to mailSender not getting set correctly, now I edited the code as it is shown below and I am not getting any exception but the code breaks at the line
MimeMessage message = mailSender.createMimeMessage();
Here is my code (both sendMail() and addNewAlarm() are inside the same class "ElementService"):
public class ElementService implements ApplicationContextAware {
private ApplicationContext ac;
public void sendMail(String toAddress, String subject, String body) throws Exception{
JavaMailSender mailSender = (JavaMailSender) ac.getBean("mailSender");
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("xxx#gmail.com");
helper.setTo(toAddress);
helper.setSubject(subject);
helper.setText(body);
}catch (MessagingException e) {
throw new MailParseException(e);
}
try{
mailSender.send(message);
}
catch(Exception e){
throw e;
}
}
//I want an email to be sent every 30 seconds
#Scheduled(fixedDelay = 30*1000)
public void function2RepeatEvery30Seconds()
{
MailService mailer = (MailService) ac.getBean("mailService");
mailer.sendMail("xxx#hotmail.com","subject","body");
//does other stuff..
}
#Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
this.ac = ac;
}
}
These are the beans in my xml:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- SMTP settings -->
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="***#gmail.com" />
<property name="password" value="*****" />
<property name="javaMailProperties">
<!-- additional properties specific to JavaMail -->
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
In debug mode I can see that mailSender has been set according to the properties shown on the mailSender bean.

I finally did it!! Thanks to Serge Ballesta of course. I should have been using log4j all along... I researched the Exception MessageRemovedIOException and I found this post java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail where there is a suggestion in the comments to change
<dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.2</version> </dependency>
to
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency>
I also had to change this:
<prop key="mail.smtp.starttls.enable">true</prop>
to this:
<prop key="mail.smtp.starttls.enable">false</prop>
Thank you very much for your time and advice #Serge Ballesta!

Ok, obviously the mailSender is null which causes the error. My guess would be that your #Autowired annotation is not processed. Do you have AutowiredAnnotationBeanPostProcessor registered? You can do that for example by using <context:annotation-config /> in your Spring configuration.
Other option (without using #Autowired) is to manually specify the dependency on mailSender in your mailService bean definition like so:
<bean id="mailService" class="gr.mobics.allweb.service.MailService" scope="singleton">
<property name="mailSender" ref="mailSender" />
</bean>
I have not tested this, but it seems like this is the cause of your problem. If these solutions don't work you, leave a comment and I'll try to update the answer.

Related

Spring-batch Entity Manager becomes null after init

I'm currently implementing a Spring-batch that reads and writes to files BUT also needs to do CRUD operations on a database.
I've tried to simply define an Entity manager in my xml configuration, and use it in my DAO class. However, right after the init, the EntityManager becomes null.
Can anyone help me with this ? (a solution or a link via something usable would be perfect).
My batchContext.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${batch.datasource.driverClassName}"/>
<property name="url" value="${batch.datasource.url}"/>
<property name="username" value="${batch.datasource.username}"/>
<property name="password" value="${batch.datasource.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
</bean>
<bean id="entityManagerFactory" name="entTransactionMgr" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="persistenceXmlLocation" value="classpath:/META-INF/spring/persistence.xml" /> -->
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="packagesToScan" value="${jpa.scan.packages}"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<!-- Custom jpaDialect pour le deuxieme batch:job-repository-->
<property name="jpaDialect">
<bean class="fr.mma.soecm.batchfacade.util.CustomHibernateJpaDialect" />
</property>
<property name="jpaProperties">
<props>
<!-- multiple props here-->
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- mode="aspectj" -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<batch:job-repository id="jobRepository" data-source="dataSource" transaction-manager="transactionManager"/>
<!-- Jobs held separatelly -->
<import resource="batchContext-job.xml"/>
My DAO
#Repository("batchJobDao")
#Transactional
public class BatchJobDaoImpl implements BatchJobDao{
#PersistenceContext(unitName="persistenceUnit")
#Autowired
private EntityManager entityManager;
// #PersistenceContext(unitName="persistenceUnit", type=PersistenceContextType.EXTENDED)
// public void setEntityManager(EntityManager entityManager) {
// System.out.println("Setting Entity Manager :" + entityManager);
// this. entityManager = entityManager;
// }
#PostConstruct
public void init(){
if (entityManager == null){
System.out.println(" Entity Manager is null");
} else {
System.out.println(" Entity Manager is not null");
getAllJobExecutions();
}
}
private static final String RECHERCHER_JOB_EXECUTION = "Select bje from BatchJobExecution bje";
#SuppressWarnings("unchecked")
#Override
#Transactional("transactionManager")
public List<BatchJobExecution> getAllJobExecutions(){
// EntityManagerFactory emf=Persistence.createEntityManagerFactory("entTransactionMgr");
// EntityManager em=emf.createEntityManager();
Query query = entityManager.createQuery(RECHERCHER_JOB_EXECUTION, BatchJobExecution.class);
List<BatchJobExecution> executions = (List<BatchJobExecution>) query.getResultList();
System.out.println("EXES : " + executions);
return executions;
}
}
There is some code commented out because I've tried multiple aproaches (changing the persistence context type, recovering the entity manager "manually", having a persistence.xml file for the entityManager) without succes.
My output when running the job is (without all the extra lines..):
Entity Manager is not null
EXES : [fr.mma.soecm.batchfacade.domain.BatchJobExecution#10e6c33,...]
[BatchService] - Synchronous job launch
[AbstractStep] - Encountered an error executing the step
Caused by: java.lang.NullPointerException
And the null pointer, on debug, is throws by the EntityManager being null when I call the "createQuery" in my DAO.
Thanks for your help.
I'll keep searching on my end.. God Speed!
As mentioned in the comment above, my aparent problem was due to the fact that I was trying to call the Service or the DAO in the Constructor of the Step.
After moving the Service call in the "doRead()" method, I could perform all CRUD operations with the EntityManager.
Please let me know if anyone has questions about this/and how to make it work otherwise, as I've not found any explanation on the internet, since I've began searching last week.

How to create Configuration class with Beans in spring boot?

I am converting a project done using spring jms into spring boot project. I dont know how to convert the context.xml in spring jms into the configuration class in spring boot. My context.xml is as follows
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>file:./config-env-receiver.properties</value>
</property>
</bean>
<bean id="stepConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName">
<value>${mq.hostname.step}</value>
</property>
<property name="port">
<value>${mq.port.step}</value>
</property>
<property name="channel">
<value>${mq.channel.step}</value>
</property>
<property name="queueManager">
<value>${mq.queuemanager.step}</value>
</property>
<property name="transportType">
<value>1</value>
</property>
</bean>
<bean id="jmsDestination" class="com.ibm.mq.jms.MQQueue">
<constructor-arg value="${mq.queuename.step}" />
</bean>
<bean
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="stepConnectionFactory" />
<property name="sessionTransacted" value="true" />
<property name="destinationName" value="${mq.queuename.step}" />
<property name="exceptionListener" ref="exceptionListener" />
<property name="messageListener" ref="stepOutListenerItemCreateUpdate" />
</bean>
<bean id="exceptionListener" class="com.message.view.CustomException">
</bean>
<bean id="stepOutListenerItemCreateUpdate"
class="com.message.view.WMQueueMessageConsumer">
</bean>
<bean id="springConnectionFactory"
class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="stepConnectionFactory" />
</bean>
<bean id="jmsTemplateStep" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="springConnectionFactory" />
<property name="defaultDestination" ref="jmsDestination" />
</bean>
<context:component-scan base-package="com.message.view">
</context:component-scan>
I tried creating the Application.class as follows.
package hello;
import java.util.Arrays;
import javax.jms.JMSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import com.ibm.mq.jms.MQQueue;
import com.ibm.mq.jms.MQQueueConnectionFactory;
#SpringBootApplication
//#ImportResource("classpath:context_receiver.xml")
public class Application {
#Autowired
public CustomException customException;
#Autowired
public MessageListener messageListener;
#Bean
public MQQueueConnectionFactory getMQconnectionfactory(){
MQQueueConnectionFactory mqconfactory=new MQQueueConnectionFactory();
try {
mqconfactory.setHostName("*******");
mqconfactory.setPort(*****);
mqconfactory.setChannel("**********");
mqconfactory.setQueueManager("********");
mqconfactory.setTransportType(1);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mqconfactory;
}
#Bean
public MQQueue getMQQueue(){
return new MQQueue();
}
#Bean
public DefaultMessageListenerContainer getDefaultMessageListenerContainer(){
DefaultMessageListenerContainer defmesliscont=new DefaultMessageListenerContainer();
defmesliscont.setConnectionFactory(getMQconnectionfactory());
defmesliscont.setSessionTransacted(true);
defmesliscont.setDestinationName("********");
defmesliscont.setExceptionListener(customException);
defmesliscont.setMessageListener(messageListener);
return defmesliscont;
}
#Bean
public SingleConnectionFactory getSingleConnectionFactory(){
SingleConnectionFactory singleConnectionFactory=new SingleConnectionFactory();
singleConnectionFactory.setTargetConnectionFactory(getMQconnectionfactory());
return singleConnectionFactory;
}
#Bean
public JmsTemplate getJmsTemplate(){
JmsTemplate jmsTemplate=new JmsTemplate();
jmsTemplate.setConnectionFactory(getSingleConnectionFactory());
jmsTemplate.setDefaultDestination(getMQQueue());
return jmsTemplate;
}
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
But am getting this error.
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: ; nested exception is java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:383)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:162)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:296)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:240)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at hello.Application.main(Application.java:81)
Caused by: java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.core.annotation.AnnotationAttributes.doGet(AnnotationAttributes.java:117)
at org.springframework.core.annotation.AnnotationAttributes.getStringArray(AnnotationAttributes.java:70)
at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:69)
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:379)
... 13 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: ; nested exception is java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:383)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:162)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:296)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:240)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at hello.Application.main(Application.java:81)
Caused by: java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.core.annotation.AnnotationAttributes.doGet(AnnotationAttributes.java:117)
at org.springframework.core.annotation.AnnotationAttributes.getStringArray(AnnotationAttributes.java:70)
at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:69)
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:379)
... 13 more
I have even tried importing the context.xml using #ImportResource. But that too is not working. Though i prefer configuring it through the Application.class.
Please tell me what am doing wrong. Thanks.
I've got it working. Here is the snippet from thre working pom file
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
Upgrade you spring version to 4.1.5.RELEASE
I've got the same issue.
Looks like the problem is in incompatibility of EnableAutoConfiguration which is part of SpringBootApplication and https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java. EnableAutoConfiguration has exclude as Class [], but AnnotationAttributes expects String []. Most likely the versions are incompatible. I did not come up with solution yet though.
close idea
regenerate idea configuration files
$ mvn idea:clean
$ mvn idea:idea
reimport projects
run again in the idea

OpenJPA with Oracle - NullPointerException while creating the EntityManager

I am new to OpenJPA. When I tried to write a sample program with OpenJPA and Oracle, I am getting a NullPointerException while creating the EntityManager.
Sample program is
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testjpa");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
Customer customer = new Customer();
customer.setFirstName("Charles");
customer.setLastName("Dickens");
customer.setCustType("RETAIL");
customer.setStreet("10 Downing Street");
customer.setAppt("1");
customer.setCity("NewYork");
customer.setZipCode("12345");
em.persist(customer);
userTransaction.commit();
em.close();
entityManagerFactory.close();
}
persistence.xml is
<persistence-unit name="testjpa">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>sample.jpa.entity.Customer</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="oracle(DriverVendor=oracle)" />
<property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="openjpa.ConnectionDriverName" value="oracle.jdbc.driver.OracleDriver" />
<property name="openjpa.ConnectionUserName" value="xxxxx" />
<property name="openjpa.ConnectionPassword" value="xxxxx" />
<property name="openjpa.Log" value="SQL=TRACE" />
</properties>
</persistence-unit>
Stacktrace is
Exception in thread "main" java.lang.NullPointerException
at sample.jpa.main.TestJPA.main(TestJPA.java:16)
This is happening at
EntityManager em = entityManagerFactory.createEntityManager();
Can anyone help me to resolve this?
Like Eelke told you already: You have to post the exact stack trace. There is no chance to start debugging this without the stack.
I also hope that his whitespace behind "Persistence" in your code snippet is just a typo:
EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("testjpa");
Sebastian

problems with ApplicationContext and Spring batch

i'm working with Spring batch, i've done the batch job, configured with an xml file,
i also put all the Quartz configuration in that xml file, (the trigger, schedulerFactoryBean and jobDetail); this is a java project, and i'm trying to load the application context, as an stand alone in a main class; as far as the documentation says, this should make Quartz to start running and is doing it, the problem is when the job runs with the trigger and calls the service, is like all the Autowired beans hadn’t had been loaded, so is giving me an NullpointerException…
this is the code that the job calls after the trigger is fired, and when the JobParametersBuilder is created is when everything crash, Quartz still running though...
could someone helpme with this?
//class called by the job
public class MainJobClass {
private static Logger log = Logger.getLogger(MainJobClass.class);
#Autowired
private SimpleJobLauncher launcher;
#Autowired
private Job job;
public void executeJob(){
try{
log.info("***** Staring job......");
JobParametersBuilder builder = new JobParametersBuilder();
builder.addDate("date", new Date());
builder.addString("sendEmailJob", "Send email to approvers");
JobParameters parameters = builder.toJobParameters();
launcher.run(job, parameters);
}catch(Exception e){
log.error("Error on executing job"+e.fillInStackTrace());
}
}
public void setLauncher(SimpleJobLauncher launcher) {
this.launcher = launcher;
}
public void setJob(Job job) {
this.job = job;
}
simple main method calling App context:
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("/com/ge/grt/email/grt_email_send.xml");
}
error line:
INFO [DefaultQuartzScheduler_Worker-1] (MainJobClass.java:29) - ***** Staring job......
ERROR [DefaultQuartzScheduler_Worker-1] (MainJobClass.java:40) - Error on executing jobjava.lang.NullPointerException
this are the Quartz beans on the xml file:
<!-- Scheudler Factory bean, the job will run when the context is loaded -->
<bean id="schedulerFactoryBean"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="beanTrigger"></ref>
</list>
</property>
</bean>
<!-- definition of the trigger -->
<!-- defining the execution date: (once every week on monday at 8:00 AM) -->
<bean id="beanTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobDetail" />
<property name="misfireInstructionName" value="MISFIRE_INSTRUCTION_FIRE_ONCE_NOW"/>
<!-- <property name="cronExpression" value="0 0 8 ? * MON" /> -->
<property name="cronExpression" value="0 0/1 * * * ?" />
</bean>
<!-- definiton of job detail bean -->
<bean id="jobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="mainJobClass" />
<property name="targetMethod" value="executeJob" />
<property name="concurrent" value="false"></property>
</bean>
Try org.springframework.scheduling.quartz.JobDetailBean along with jobDataAsMap for job class DI
Ex:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html#scheduling-quartz-jobdetail

junit 4 testing with spring 3.0 and Hibernate 3 in Eclipse - LazyInitializationException

I'm getting a LazyInitializationException trying to test my DAO methods using the tool stack defined in the title. My understanding is that my test must be running outside the hibernate session, or it has been closed before I try to read children objects from my DAO. From reading the documentation, I understood that using the #TransactionConfiguration tag would allow me to define the transaction manager in which to run the tests.
I've read the documentation multiple times and a zillion forum posts. Still slamming my head into my keyboard... What am I missing? Thanks for your help!
my unit test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:/WEB-INF/applicationContext-db.xml",
"classpath:/WEB-INF/applicationContext-hibernate.xml",
"classpath:/WEB-INF/applicationContext.xml" })
#TestExecutionListeners({DependencyInjectionTestExecutionListener.class, CleanInsertTestExecutionListener.class})
#DataSetLocation("test/java/com/yada/yada/dao/dbunit-general.xml")
#TransactionConfiguration(transactionManager="transactionManager", defaultRollback = true)
#Transactional
public class RealmDAOJU4Test {
#Autowired
private DbUnitInitializer dbUnitInitializer;
#Autowired
private RealmDAO realmDAO;
#Test
public void testGetById() {
Integer id = 2204;
Realm realm = realmDAO.get(id);
assertEquals(realm.getName().compareToIgnoreCase(
"South Technical Realm"), 0);
assertEquals(8, realm.getRealmRelationships().size());
}
}
my applicationContext-hibernate.xml:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="useTransactionAwareDataSource" value="true" />
... other properties removed ...
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
my dao definition in applicationContext.xml
<bean id="realmDAOTarget" class="com.yada.yada.dao.hibernate.RealmDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="realmDAO" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.yada.yada.dao.RealmDAO</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
<value>realmDAOTarget</value>
</list>
</property>
</bean>
well, for anyone following along at home, here's what I missed:
TransactionalTestExecutionListener
it is required in the #TestExecutionListeners list for the #Transactional annotation to have any effect.