I am creating bean class of JavaMailSender and autowired the javamailsender but i getting error
package com.websystique.springsecurity.service;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.websystique.springsecurity.dao.EmployeeDao;
import com.websystique.springsecurity.model.Employee;
#Service
#Transactional
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDAOImpl;
Employee Employee;
#Autowired
private JavaMailSender mailSender;
#Autowired
private SimpleMailMessage simpleMailMessage;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
#Transactional
public void addEmployee(Employee employee) {
employeeDAOImpl.addEmployee(employee);
StringBuilder subject = new StringBuilder();
subject.append("User ");
subject.append(employee.getFirstname());
subject.append(" ");
subject.append(employee.getLastname());
subject.append(" has been added");
String content = subject.toString()+" Successfully!";
sendMail("", content,subject.toString(),employee.getEmail(),"D:\\log.pdf");
}
#Transactional
public List<Employee> getAllEmployees() {
return employeeDAOImpl.getAllEmployees();
}
#Transactional
public void deleteEmployee(Integer employeeId) {
employeeDAOImpl.deleteEmployee(employeeId);
}
#Transactional
public Employee getEmployee(int empid) {
return employeeDAOImpl.getEmployee(empid);
}
#Transactional
public Employee updateEmployee(Employee employee) {
Employee emp = employeeDAOImpl.updateEmployee(employee);
StringBuilder subject = new StringBuilder();
subject.append("User ");
subject.append(emp.getFirstname());
subject.append(" ");
subject.append(emp.getLastname());
subject.append(" has been updated");
String content = subject.toString()+" Successfully!";
sendMail("", content,subject.toString(),emp.getEmail(),"D:\\log.pdf");
return emp;
}
#Transactional
public void setEmployeeDAO(EmployeeDao employeeDAO) {
this.employeeDAOImpl = employeeDAO;
}
#Transactional
public void sendMail(String dear, String content,String subject,String
toEmail,String filePath) {
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(new InternetAddress("saranpartneritech#gmail.com"));
helper.setTo(new InternetAddress(toEmail));
helper.setSubject(subject);
helper.setText(content);
if(filePath!=null){
FileSystemResource file = new FileSystemResource(filePath);
helper.addAttachment(file.getFilename(), file);
}
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}
I couldn't create the bean class for bean id="mailSender". i am working on it for past two days please get me out of it.
<context:component-scan base-
package="com.websystique.springsecurity.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/static/**" location="/static/" />
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionService
FactoryBean">
<property name="converters">
<list>
<bean id="roleToUserProfile"
class="com.websystique.springsecurity.util.RoleToUserProfileConverter" />
</list>
</property>
</bean>
<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="saranpartneritech#gmail.com" />
<property name="password" value="Saran2595" />
<property name="javaMailProperties">
<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>
<!--
<bean id="mailMail" class="com.mkyong.common.MailMail">
<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="customeMailMessage" />
</bean>
<bean id="customeMailMessage"
class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="saranpartneritech#gmail.com" />
<property name="subject" value="Customer Report" />
<property name="text">
<value>
<![CDATA[
Dear %s,
Mail Content : %s
]]>
</value>
</property>
</bean> -->
</beans>
And error page
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'employeeController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
com.websystique.springsecurity.service.EmployeeService
com.websystique.springsecurity.controller.EmployeeController.employeeServiceImpl;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'employeeServiceImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
org.springframework.mail.javamail.JavaMailSender
com.websystique.springsecurity.service.EmployeeServiceImpl.mailSender;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.mail.javamail.JavaMailSender] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
your component scan includes only com.websystique.springsecurity.controller. So it will not be able to scan other packages to inject the dependencies. enable the component scan on top package(com.websystique.springsecurity) and override bean definations (if required) in xml file.
Try this in your xml and if it works revert back
Related
MySQL, postgresql
I want to put the same data in the same name table.
Both databases have the same table.
error
WARN 2017-07-04 14:53:03 o.s.c.s.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tempMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
INFO 2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
INFO 2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
ERROR 2017-07-04 14:53:03 o.s.t.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#7af44dd0] to prepare test instance [jp.co.ui2.dev.server.c_one.tempServiceTest#26d8c9da]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:357) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:587) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:546) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:712) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:685) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:354) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 39 common frames omitted
test.properties
//mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:8888/testdb
jdbc.username=test
jdbc.password=test
//postgresql
jdbc.driverClassName2=org.postgresql.Driver
jdbc.url2=jdbc:postgresql://localhost:5432/postgres
jdbc.username2=postgres
jdbc.password2=postgres
TestConfig.java
#Configuration
#Import({ testServerConfig.class })
public class TestConfig
{
#Bean
public PropertiesFactoryBean prop() {
PropertiesFactoryBean f = new PropertiesFactoryBean();
f.setLocations(new Resource[] {
new FileSystemResource("src/main/webapp/WEB-INF/config.properties"),
new ClassPathResource("test.properties", getClass())
});
return f;
}
}
tempServiceTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = TestConfig.class, loader =AnnotationConfigContextLoader.class)
public class ShopInfoServiceTest extends AbstractServiceTest
{
#Autowired
private tempMasterService tempService;
#Test
public void testCustomCode()
{
// insert
doInTransaction(new Runnable() {
#Override
public void run() {
tempMaster info = createTemp( );
tempService.insertTempMaster(info);
}
});
}
private tempMaster createTemp () {
tempMaster xxx = new tempMaster ();
xxx.setTempId(1);
xxx.setTempName("chaco1234");
xxx.setDescription("tttttt2232");
xxx.setUserId("admin");
return xxx;
}
}
testServerConfig.java
#Configuration
#ComponentScan(basePackages = { "com.co.test.dev" }, excludeFilters = {
#Filter(type = FilterType.ANNOTATION, value = Controller.class),
#Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
#EnableTransactionManagement
#EnableScheduling
#EnableCaching
#ImportResource("classpath:job-context.xml")
public class testServerConfig
{
#Autowired
private ApplicationContext ctx;
#Autowired
private ResourceLoader resourceLoader;
#Value("#{prop['jdbc.driverClassName'] ?: ''}")
private String jdbcDriverClassName;
#Value("#{prop['jdbc.url'] ?: ''}")
private String jdbcUrl;
#Value("#{prop['jdbc.username'] ?: ''}")
private String jdbcUsername;
#Value("#{prop['jdbc.password'] ?: ''}")
private String jdbcPassword;
#Value("#{prop['jdbc.driverClassName2'] ?: ''}")
private String jdbcDriverClassName2;
#Value("#{prop['jdbc.url2'] ?: ''}")
private String jdbcUrl2;
#Value("#{prop['jdbc.username2'] ?: ''}")
private String jdbcUsername2;
#Value("#{prop['jdbc.password2'] ?: ''}")
private String jdbcPassword2;
#Value("#{prop['hibernate.dialect2'] ?: ''}")
private String hibernateDialect2;
#Value("#{prop['jdbc.initialSize'] ?: '0'}")
private int jdbcInitialSize;
#Value("#{prop['jdbc.maxActive'] ?: '50'}")
private int jdbcMaxActive;
#Value("#{prop['jdbc.maxIdle'] ?: '5'}")
private int jdbcMaxIdle;
#Value("#{prop['jdbc.maxWait'] ?: '5000'}")
private int jdbcMaxWait;
#Value("#{prop['jdbc.minIdle'] ?: '0'}")
private int jdbcMinIdle;
#Value("#{prop['jdbc.testWhileIdle'] ?: 'false'}")
private boolean jdbcTestWhileIdle;
#Value("#{prop['jdbc.testOnBorrow'] ?: 'false'}")
private boolean jdbcTestOnBorrow;
#Value("#{prop['jdbc.validationQuery'] ?: ''}")
private String jdbcValidationQuery;
#Value("#{prop['hibernate.hbm2ddl.auto'] ?: 'update'}")
private String hibernateDDLAuto;
#Value("#{prop['hibernate.dialect'] ?: ''}")
private String hibernateDialect;
#Value("#{prop['hibernate.search.indexBase'] ?: ''}")
private String searchIndexBase;
#Value("#{prop['hibernate.packages.to.scan'] ?: ''}")
private String packagesToScan;
protected String getRealPath(String path)
{
if ((ctx != null) && (ctx instanceof WebApplicationContext)
&& (((WebApplicationContext) ctx).getServletContext() != null)) return ((WebApplicationContext) ctx)
.getServletContext().getRealPath(path);
else return "src/main/webapp/" + path;
}
#Bean
public PropertiesFactoryBean prop()
{
String path = getRealPath("/WEB-INF/config.properties");
PropertiesFactoryBean f = new PropertiesFactoryBean();
f.setLocation(new FileSystemResource(path));
return f;
}
#Bean(name="dataSource")
public DataSource dataSource()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriverClassName);
ds.setUrl(jdbcUrl);
ds.setUsername(jdbcUsername);
ds.setPassword(jdbcPassword);
ds.setInitialSize(jdbcInitialSize);
ds.setMaxActive(jdbcMaxActive);
ds.setMaxIdle(jdbcMaxIdle);
ds.setMaxWait(jdbcMaxWait);
ds.setMinIdle(jdbcMinIdle);
ds.setTestWhileIdle(jdbcTestWhileIdle);
ds.setValidationQuery(jdbcValidationQuery);
return ds;
}
#Bean(name="dataSource2")
public DataSource dataSource2()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriverClassName2);
ds.setUrl(jdbcUrl2);
ds.setUsername(jdbcUsername2);
ds.setPassword(jdbcPassword2);
ds.setInitialSize(jdbcInitialSize);
ds.setMaxActive(jdbcMaxActive);
ds.setMaxIdle(jdbcMaxIdle);
ds.setMaxWait(jdbcMaxWait);
ds.setMinIdle(jdbcMinIdle);
ds.setTestWhileIdle(jdbcTestWhileIdle);
ds.setValidationQuery(jdbcValidationQuery);
return ds;
}
#Bean(name="entityManagerFactoryBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
if (packagesToScan != null) {
String[] pts = packagesToScan.split(",");
emf.setPackagesToScan(pts);
}
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties p = new Properties();
p.setProperty("hibernate.archive.autodetection", "class");
p.setProperty("hibernate.dialect", hibernateDialect);
p.setProperty("hibernate.show_sql", "false");
p.setProperty("hibernate.format_sql", "true");
p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
//naming-strategy
p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
emf.setJpaProperties(p);
return emf;
}
#Bean(name="entityManagerFactoryBean2")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean2()
{
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
if (packagesToScan != null) {
String[] pts = packagesToScan.split(",");
emf.setPackagesToScan(pts);
}
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties p = new Properties();
p.setProperty("hibernate.archive.autodetection", "class");
p.setProperty("hibernate.dialect2", hibernateDialect2);
p.setProperty("hibernate.show_sql", "false");
p.setProperty("hibernate.format_sql", "true");
p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
//naming-strategy
p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
emf.setJpaProperties(p);
return emf;
}
#Bean(name="transactionManager")
public PlatformTransactionManager transactionManager()
{
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return tm;
}
#Bean(name="transactionManager2")
public PlatformTransactionManager transactionManager2()
{
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactoryBean2().getObject());
return tm;
}
#Bean
public EhCacheCacheManager cacheManager()
{
EhCacheCacheManager cm = new EhCacheCacheManager();
cm.setCacheManager(ehcache().getObject());
return cm;
}
#Bean
public EhCacheManagerFactoryBean ehcache()
{
EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
factory.setConfigLocation(resourceLoader.getResource("classpath:ehcache.xml"));
return factory;
}
#Bean(name = "configSftpSessionfactoryId")
public DefaultSftpSessionFactory sftpSessionFactory() {
DefaultSftpSessionFactory sftp = new DefaultSftpSessionFactory();
sftp.setHost(sftpHost);
sftp.setPort(sftpPort);
sftp.setUser(sftpUser);
sftp.setPassword(sftpPassword);
if (sftpPrivateKey != null && !"".equals(sftpPrivateKey)) {
sftp.setPrivateKey(resourceLoader.getResource(sftpPrivateKey));
sftp.setPrivateKeyPassphrase(sftpPrivateKeyPassphrase);
}
sftp.setAllowUnknownKeys(true);
return sftp;
}
}
tempMasterServiceImpl
#Service
#Transactional
#SwabAdminAuthCheck
public class tempMasterImpl implements tempMasterService{
private Logger logger = LoggerFactory.getLogger(getClass());
#PersistenceContext
private EntityManager em;
#Override
public void insertTempMaster(tempMaster obj) throws SwabException {
Query keyq = em.createQuery("select tempId from tempMaster where userId = :userId");
keyq.setParameter("userId", obj.getUserId());
Integer tmepId = null;
try{
tempId = (Integer)keyq.getSingleResult();
obj.setTempId( tempId );
} catch (NoResultException nre){
}
tempMaster searchData = em.find(tempMaster.class, obj);
if (searchData == null) {
logger.debug("insert");
em.persist(obj);
} else {
logger.debug("update");
em.merge(obj);
}
}
}
Will this source help?
datasourse-config.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="dataSource2"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName2}" />
<property name="url" value="${jdbc.url2}" />
<property name="username" value="${jdbc.username2}" />
<property name="password" value="${jdbc.password2}" />
</bean>
<context:property-placeholder location="classpath:config.properties" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactoryBean" />
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactoryBean2" />
</bean>
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactoryBean2"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource2" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect2}</prop>
</props>
</property>
</bean>
persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect" />
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver" />
</properties>
</persistence-unit>
</persistence>
spring-config.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<!-- 非同期処理タスクExecutor -->
<bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<!-- バリデーションプロセッサ -->
<bean id="validatingItemProcessor" class="org.springframework.batch.item.validator.ValidatingItemProcessor">
<property name="validator">
<bean class="org.springframework.batch.item.validator.SpringValidator">
<property name="validator">
<!-- Hibernate バリデータ -->
<bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</property>
</bean>
</property>
</bean>
<!-- property config file -->
<bean id="propertyFilebean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="config.properties"/>
</bean>
<bean id="dummyTasklet" class="jp.co.ui2.sms.batch.tasklet.DummyTasklet">
<property name="batchStatus">
<value type="org.springframework.batch.core.BatchStatus">FAILED</value>
</property>
</bean>
</beans>
First I want to start off saying that I'm a bit new to Spring so the conceptual aspect of it is a bit unclear, and thusly preventing me from understanding the implementation. I'm trying to integrate hibernate and spring together, but I continually get this error.
Error creating bean with name 'facade' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'bankDAO' of bean class [data.Facade]: Bean property 'bankDAO' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
org.springframework.beans.factory.BeanCreationException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
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 JUnitTest.HibernateTest.setup(HibernateTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'bankDAO' of bean class [data.Facade]: Bean property 'bankDAO' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1064)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:924)
... 37 more
Here's my BankDAO class
package data;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import beans.Bank;
public class BankDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Bank get(int id) {
return (Bank) sessionFactory.getCurrentSession().get(Bank.class, id);
}
#Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Bank load(int id) {
return (Bank) sessionFactory.getCurrentSession().load(Bank.class, id);
}
}
Façade class
package data;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.*;
import java.util.List;
public class Facade {
private SessionFactory sf = new Configuration().configure().buildSessionFactory();
private static ApplicationContext contxt;
public static void getContext() {
contxt = new ClassPathXmlApplicationContext("beans.xml");
}
public void createAccount(AccountDAO account){
contxt.getBean(AccountDAO.class).insert(account);
System.out.println("Event was inserted");
}
public List<Account> getAllAccounts(){
return contxt.getBean(AccountDAO.class).getAll();
}
}
Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Use #Transactional instead of <tx:advice> -->
<tx:annotation-driven />
<!-- DataSource bean -->
<bean name="ds" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="url" value="localhost" />
</bean>
<!-- SessionFactory -->
<bean name="sf"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="ds" />
<property name="packagesToScan" value="beans" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.pool_size">20</prop>
<prop key="hibernate.dialect"> org.hibernate.dialect.Oracle10gDialect </prop>
<prop key="show_sql">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean name="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sf" />
</bean>
<!-- DAO beans -->
<bean name="bankDAO" class="data.BankDAO"> <property name="sessionFactory" ref="sf" /> </bean>
<bean name="accountDAO" class="data.AccountDAO"> <property name="sessionFactory" ref="sf" /> </bean>
</bean>
<!-- Facade bean -->
<bean name="facade" class="dataTier.DataFacade">
<property name="bankDAO" ref="bankDAO" />
<property name="accountDAO" ref="accountDAO" />
</bean>
</beans>
Any help is appreciated thank you.
Error log clearly telling that it is not finding setter for bankDAO
Error creating bean with name 'facade' defined in class path resource
[beans.xml]: Error setting property values; nested exception is
org.springframework.beans.NotWritablePropertyException: Invalid
property 'bankDAO' of bean class [data.Facade]: Bean property
'bankDAO' is not writable or has an invalid setter method. Does the
parameter type of the setter match the return type of the getter?
To fix it, create property bankDAO along with setter/getter as follows:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.*;
import java.util.List;
public class Facade {
private SessionFactory sf = new Configuration().configure()
.buildSessionFactory();
private static ApplicationContext contxt;
private BankDAO bankDAO;
public static void getContext() {
contxt = new ClassPathXmlApplicationContext("beans.xml");
}
public void createAccount(AccountDAO account) {
contxt.getBean(AccountDAO.class).insert(account);
System.out.println("Event was inserted");
}
public List<Account> getAllAccounts() {
return contxt.getBean(AccountDAO.class).getAll();
}
public BankDAO getBankDAO() {
return bankDAO;
}
public void setBankDAO(BankDAO bankDAO) {
this.bankDAO = bankDAO;
}
}
Also check bean named "facade", as from error logs it seems it should be:
<!-- Facade bean -->
<bean name="facade" class="dataTier.Facade">
<property name="bankDAO" ref="bankDAO" />
<property name="accountDAO" ref="accountDAO" />
</bean>
not
<!-- Facade bean -->
<bean name="facade" class="dataTier.DataFacade">
<property name="bankDAO" ref="bankDAO" />
<property name="accountDAO" ref="accountDAO" />
</bean>
I am developing Spring Batch - MongoDB to XML example. In this example, when I run the main method I see the below error is cominng. Please guide on the below error. I tried to find the solution on the web, but I dont find anything helpful on the web yet.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'mongodbItemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongodbItemReader' defined in class path resource [job-report.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: A type to convert the input into is required.
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1492)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1237)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:740)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at com.mkyong.App.main(App.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongodbItemReader' defined in class path resource [job-report.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: A type to convert the input into is required.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1589)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 15 more
Caused by: java.lang.IllegalStateException: A type to convert the input into is required.
at org.springframework.util.Assert.state(Assert.java:392)
at org.springframework.batch.item.data.MongoItemReader.afterPropertiesSet(MongoItemReader.java:200)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585)
... 22 more
database.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<!-- connect to mongodb -->
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="yourdb" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>
context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
<!-- stored job-meta in memory -->
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
</beans>
job-report.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch" xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="mongodbItemReader" writer="xmlItemWriter" commit-interval="1">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="classpath:xml/report.xml" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="record" />
</bean>
<!-- ==== Solution-1 ==== -->
<bean id="reportMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>com.mkyong.Report</value>
</property>
</bean>
<!-- ==== Solution-2 ==== -->
<!-- <bean id="reportMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="aliases">
<util:map id="aliases">
<entry key="record" value="com.mkyong.Report" />
</util:map>
</property>
<property name="converters">
<array>
<ref bean="reportConverter" />
</array>
</property>
</bean> -->
<bean id="reportConverter" class="com.mkyong.ReportConverter" />
</beans>
Repoer.java
#XmlRootElement(name = "record")
public class Report {
private int id;
private Date date;
private long impression;
private int clicks;
private BigDecimal earning;
#XmlAttribute(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#XmlElement(name = "impression")
public long getImpression() {
return impression;
}
public void setImpression(long impression) {
this.impression = impression;
}
#XmlElement(name = "clicks")
public int getClicks() {
return clicks;
}
public void setClicks(int clicks) {
this.clicks = clicks;
}
#XmlElement(name = "earning")
public BigDecimal getEarning() {
return earning;
}
public void setEarning(BigDecimal earning) {
this.earning = earning;
}
}
App.java
public class App {
public static void main(String[] args) {
String[] springConfig = { "database.xml", "context.xml", "job-report.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("reportJob");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
Could you help on this?
As the error points out, you need to set the "type" property on your "mongodbItemReader" bean.
See MongoItemReader javadoc.
Example:
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="Report.class" />
</bean>
You might need to specify the package name in the value (I haven't tried it).
Thank you #Sergio, it was great help from you, but below configuration works.
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="com.mkyong.model.Report" />
<property name="query" value="{'_id':{$gt:0} }" />
<property name="sort">
<util:map>
<entry key="id" value="#{T(org.springframework.data.domain.Sort.Direction).ASC}" />
</util:map>
</property>
</bean>
The only problem I see, nothing is getting write into the XML file. I will raise a separate question for this issue.
Note: The main reason of this error is you need to set <property name="targetType" value="com.mkyong.model.Report" /> this property correctly.
You can also refer: http://www.mkyong.com/spring-batch/how-to-convert-date-in-beanwrapperfieldsetmapper/ as another solution.
1.I am very new in spring and this question has been asked many times but still i am not able to figure out the wrong things.And getting these exceptions.
This is my console output
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sidSearchController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jlcindia.spring.mvc.SidValidator com.jlcindia.spring.mvc.SidSearchController.sidValidator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver] for bean with name 'org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver#0' defined in ServletContext resource [/WEB-INF/jlcindia-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1055)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
javax.servlet.GenericServlet.init(GenericServlet.java:212)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
java.lang.Thread.run(Thread.java:619)
Controller class
#Controller
public class SidSearchController
{
#Autowired
private SidValidator sidValidator;
#RequestMapping(value="/searchStudent",method=RequestMethod.POST)
#ExceptionHandler({StudentNotFoundException.class})
public String searchStudent(#ModelAttribute("sidSearchCommand")SidSearchCommand sidCommand,Errors errors,HttpServletRequest req,Model model){
System.out.println("contact controller");
sidValidator.validate(sidCommand, errors);
if(errors.hasErrors()){
return "sidsearch";
}
String sid=sidCommand.getSid();
String results="";
if(sid.equals("sim-123")||sid.equals("sim-999")) {
StudentTO sto=new StudentTO();
sto.setSid(sid);
sto.setBid("B-99");
sto.setSname("srinivas");
sto.setPhone("99999");
model.addAttribute("STO", sto);
req.setAttribute("STO",sto);
results="sidresults";
}
else
{
req.setAttribute("sidSearchCommand",sidCommand);
throw new StudentNotFoundException(sid);
}return results;
}#RequestMapping(value="/sidsearch")
protected String showSearchPage(Map model) throws ServletException{
System.out.println("show search page");
SidSearchCommand sidCommand=new SidSearchCommand();
model.put("sidSearchCommand", sidCommand);
return "sidsearch";
}
}
3.mvc-dispatcher-servlet.xml:
<context:component-scan base-package="com.jlcindia.spring.mvc" />
<bean id="sidValidator" class="com.jlcindia.spring.mvc.SidValidator"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean class="org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.jlcindia.spring.mvc.StudentNotFoundException">sidsearch
</prop>
</props>
</property>
</bean>
</beans>
in your mvc-dispatcher-servlet.xml you misspelled the following: org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver
handeler is written instead of handler
I am doing sample chat application using spring mvc and redis server by following steps from
http://blog.springsource.org/2012/05/16/spring-mvc-3-2-preview-chat-sample/
the example given there is by spring java based configurations. I want to do with xml based configurations. But it is not working for me.
I am getting the issues by converting following configuration class
package org.springframework.samples.async.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.samples.async.chat.ChatController;
#Configuration
#PropertySource("classpath:redis.properties")
public class RootConfig {
#Autowired
Environment env;
#Autowired
ChatController chatController;
#Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory cf = new JedisConnectionFactory();
cf.setHostName(this.env.getProperty("redis.host"));
cf.setPort(this.env.getProperty("redis.port", int.class));
cf.setPassword(this.env.getProperty("redis.password"));
return cf;
}
#Bean
public StringRedisTemplate redisTemplate() {
return new StringRedisTemplate(redisConnectionFactory());
}
#Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer mlc = new RedisMessageListenerContainer();
mlc.setConnectionFactory(redisConnectionFactory());
mlc.addMessageListener(this.chatController , new PatternTopic("chat"));
return mlc;
}
}
The following is the Xml based configuration i am trying to use instead of above java based configuration.
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="localhost" p:port="9994" p:password=""/>
<bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
<constructor-arg>
<bean class="org.springframework.samples.async.chat.ChatController"/>
</constructor-arg>
</bean>
<bean id="redisMessageListenerContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
<property name="connectionFactory" ref="redisConnectionFactory"/>
<property name="messageListeners">s
<map>
<entry key-ref="messageListener">
<bean class="org.springframework.data.redis.listener.PatternTopic">
<constructor-arg value="chat"/>
</bean>
</entry>
</map>
</property>
</bean>
The exception i am getting is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageListener' defined in ServletContext resource [/WEB-INF/spring/mvc-config.xml]: Cannot create inner bean 'org.springframework.samples.async.chat.ChatController#74b70648' of type [org.springframework.samples.async.chat.ChatController] while setting constructor argument; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.samples.async.chat.ChatController] for bean with name 'org.springframework.samples.async.chat.ChatController#74b70648' defined in ServletContext resource [/WEB-INF/spring/mvc-config.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.samples.async.chat.ChatController
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:282)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:121)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:629)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:652)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:600)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:666)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:519)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:460)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:865)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at jav
a.lang.Thread.run(Thread.java:662)
ChatController.java
package org.springframework.samples.async.chat;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
#Controller
#RequestMapping("/mvc/chat")
public class ChatController implements MessageListener {
private final Map<DeferredResult<List<String>>, Integer> chatRequests =
new ConcurrentHashMap<DeferredResult<List<String>>, Integer>();
private final ChatRepository chatRepository;
#Autowired
public ChatController(ChatRepository chatRepository) {
this.chatRepository = chatRepository;
}
#RequestMapping(method=RequestMethod.GET, produces="application/json")
#ResponseBody
public DeferredResult<List<String>> getMessages(#RequestParam int messageIndex) {
final DeferredResult<List<String>> deferredResult = new DeferredResult<List<String>>(null, Collections.emptyList());
this.chatRequests.put(deferredResult, messageIndex);
deferredResult.onCompletion(new Runnable() {
#Override
public void run() {
chatRequests.remove(deferredResult);
}
});
List<String> messages = this.chatRepository.getMessages(messageIndex);
if (!messages.isEmpty()) {
deferredResult.setResult(messages);
}
return deferredResult;
}
#RequestMapping(method=RequestMethod.POST)
#ResponseBody
public void postMessage(#RequestParam String message) {
this.chatRepository.addMessage(message);
}
// Redis MessageListener contract
#Override
public void onMessage(Message message, byte[] pattern) {
for (Entry<DeferredResult<List<String>>, Integer> entry : this.chatRequests.entrySet()) {
List<String> messages = this.chatRepository.getMessages(entry.getValue());
entry.getKey().setResult(messages);
}
}
}
The complete mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven>
<mvc:async-support default-timeout="30000" />
</mvc:annotation-driven>
<mvc:view-controller path="/" view-name="chat"/>
<mvc:resources mapping="/resources/**" location="resources"/>
<context:component-scan base-package="org.springframework.samples.async.chat" />
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="cacheable" value="true" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean id="viewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
<property name="viewNames" value="*.html"/>
</bean>
<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"
p:connection-factory-ref="redisConnectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="localhost" p:port="9994" p:password=""/>
<bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
<constructor-arg>
<bean class="org.springframework.samples.async.chat.ChatController"/>
</constructor-arg>
</bean>
<bean id="redisMessageListenerContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
<property name="connectionFactory" ref="redisConnectionFactory"/>
<property name="messageListeners">
<!-- map of listeners and their associated topics (channels or/and patterns) -->
<map>
<entry key-ref="messageListener">
<bean class="org.springframework.data.redis.listener.PatternTopic">
<constructor-arg value="chat"/>
</bean>
</entry>
</map>
</property>
</bean>
</beans>
Please help me out.
I think the issue is that you are trying to do some sort of autowire by class thing in your xml with this portion (I am assuming):
<bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
<constructor-arg>
<bean class="org.springframework.samples.async.chat.ChatController"/>
</constructor-arg>
</bean>
But that is not how the xml configuration works. What the xml is doing here is trying to create a new instance of the ChatController and use it as a constructor argument to the MessageListenerAdapter. Obviously this doesn't work because your ChatController has no 0 arg constructors. What you want to do instead is reference your existing ChatController (which is marked as an #Controller and will therefore be automatically picked up by your component-scan) in the constructor argument. Something like this:
<bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
<constructor-arg>
<ref bean="chatController"/>
</constructor-arg>
</bean>
The bean being referenced by 'chatController' is your component-scanned ChatController (it is the default bean name when none is provided via the stereotype annotations or the #Qualifier annotation).