How to link database in mongodb through spring - spring

I really need some help, I have gone through an entire day of searching and still did not find anything that works.
Note : My database has username and password
And these two are the dependencies that i am working with.
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
This is my xml config file :
<?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:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo-client host="address" port="27017 credentials="username:password#databasename" />
</beans>
This is my main class which loads this xml:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import model.user;
//import org.springframework.context.support.GenericXmlApplicationContext;
public class App {
public static void main(String[] args) {
/*
ApplicationContext ctx = new AnnotationConfigApplicationContext(appConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
*/
ApplicationContext ctx = new GenericXmlApplicationContext("config.xml");
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
user user = new user();
// save
// mongoOperation.save(user);
// now user object got the created id.
System.out.println("1. user : " + user);
// query to search user
Query searchUserQuery = new Query(Criteria.where("age").is(26));
mongoOperation.findOne(searchUserQuery, user.class);
}
}
This is the error message I get:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: com.mongodb.MongoCredential.createCredential(Ljava/lang/String;Ljava/lang/String;[C)Lcom/mongodb/MongoCredential;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:687)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.GenericXmlApplicationContext.<init>(GenericXmlApplicationContext.java:70)
at core.App.main(App.java:20)
Caused by: java.lang.NoSuchMethodError: com.mongodb.MongoCredential.createCredential(Ljava/lang/String;Ljava/lang/String;[C)Lcom/mongodb/MongoCredential;
at org.springframework.data.mongodb.config.MongoCredentialPropertyEditor.setAsText(MongoCredentialPropertyEditor.java:108)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:430)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:403)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:181)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:460)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1503)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1462)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 10 more

Okay finally I was able to connect to the database, I did it using MongoClient. This is the code snippet:
MongoCredential credential = MongoCredential.createMongoCRCredential("username", "database", password);
MongoClient mongoClient = new MongoClient(new ServerAddress("address", 27017), Arrays.asList(credential));
// get handle to "mydb"
DB db = mongoClient.getDB("IODS");
// get a list of the collections in this database and print them out
Set<String> collectionNames = db.getCollectionNames();
for (final String s : collectionNames) {
System.out.println(s);
}
// get a collection object to work with
DBCollection coll = db.getCollection("try_vishal");

Related

org.springframework.core.convert.TypeDescriptor Class not found?

I was trying to do experiments about spring IOC and I write ServiceBean as well as a beans.xml file. I try to instantiate a service bean like this in my Application:
public class SpringTrialApplication {
public static void main(String[] args) throws IOException {
SpringTrialApplication main = new SpringTrialApplication();
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml",main.getClass().getClassLoader() ));
// use service bean:
ServiceBean service = (ServiceBean)factory.getBean("service");
// com.ServiceBean service = new com.MyServiceBean();
service.addUser("bill", "hello");
service.addUser("tom", "goodbye");
service.addUser("tracy", "morning");
System.out.println("tom's password is: " + service.getPassword("tom"));
if(service.findUser("tom")) {
service.deleteUser("tom");
}
}
}
And I can read the beans.xml successfully, but it failed to create a bean due to the not-found class org.springframework.core.convert.TypeDescriptor. Below is my log:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'service' defined in class path resource [beans.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/core/convert/TypeDescriptor
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:955)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:901)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at com.SpringTrialApplication.main(SpringTrialApplication.java:27)
Caused by: java.lang.NoClassDefFoundError: org/springframework/core/convert/TypeDescriptor
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:950)
... 8 more
Caused by: java.lang.ClassNotFoundException: org.springframework.core.convert.TypeDescriptor
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 9 more
Process finished with exit code 1
and my beans.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="service" class="com.MyServiceBean" />
</beans>
My workspace like this:
directory
following dependencies are used in my project:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>2.5.6</version>
</dependency>
So is that because spring framework change inner structure in 3.x? How can I solve this problem?
Make the same version in spring-beans and spring-core resolve the problem.

Cannot find class for bean with name defined in class path resource [applicationContext.xml]

I'm posting my query after visiting numerous question posted before on same context, unfortunately none of them resolved my problem. I'm trying a complete xml based configuration in spring without using any annotation. But as soon as i launch the application, i'm getting the following exception.
Cannot find class [com.kashyap.springboot.xml.JdbcConnectionXML.java]
for bean with name 'connection' defined in class path resource
[applicationContext.xml]; nested exception is
java.lang.ClassNotFoundException:
com.kashyap.springboot.xml.JdbcConnectionXML.java
Things i've already taken care of :-
Namespace for component scan re-examined.
Tag for component scan entered.
Bean tag with proper classes' qualified name re-examined.
Bean property and references re-visited.
applicationContext.xml is located on path src/main/resources so no
absolute path required.
Context initialized with ClassPathXmlApplicationContext class.
Classes are already defined with default public constructors for instantiation required by reflection.(though it is not mandatory, used it as precaution). Alas!!! none of the these things worked. Please find the classes and xml below.
package com.kashyap.springboot.xml;
public class JdbcConnectionXML {
public JdbcConnectionXML(){
System.out.println("JDBC XML Constructor Called");
}
}
package com.kashyap.springboot.xml;
public class PrototypeXMLDAO {
public PrototypeXMLDAO(){
System.out.println("PrototypeXMLDAO Constructor Called");
}
private JdbcConnectionXML connection;
public JdbcConnectionXML getConnection() {
return connection;
}
public void setConnection(JdbcConnectionXML connection) {
this.connection = connection;
}
}
package com.kashyap.springboot.xml;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringbootdevApplication {
public static void main(String[] args) {
try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");) {
PrototypeXMLDAO pdCDIOne = context.getBean(PrototypeXMLDAO.class);
PrototypeXMLDAO pdCDITwo = context.getBean(PrototypeXMLDAO.class);
System.out.println(pdCDIOne);
System.out.println(pdCDIOne.getConnection());
System.out.println(pdCDITwo);
System.out.println(pdCDITwo.getConnection());
}
}
}
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.kashyap.springboot.xml" />
<bean id="connection" class="com.kashyap.springboot.xml.JdbcConnectionXML">
</bean>
<bean id="prototype" class="com.kashyap.springboot.xml.PrototypeXMLDAO">
<property name="connection" ref="connection"></property>
</bean>
</beans>
The stack-trace on console as follows:-
Exception in thread "main"
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot
find class [com.kashyap.springboot.xml.JdbcConnectionXML.java] for
bean with name 'connection' defined in class path resource
[applicationContext.xml]; nested exception is
java.lang.ClassNotFoundException:
com.kashyap.springboot.xml.JdbcConnectionXML.java at
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1380)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:670)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:637)
at
org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1489)
at
org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1007)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:739)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at
org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:144)
at
org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:85)
at
com.kashyap.springboot.xml.SpringbootdevApplication.main(SpringbootdevApplication.java:13)
Caused by: java.lang.ClassNotFoundException:
com.kashyap.springboot.xml.JdbcConnectionXML.java at
java.net.URLClassLoader.findClass(URLClassLoader.java:381) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
org.springframework.util.ClassUtils.forName(ClassUtils.java:255) at
org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:418)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1428)
at
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1372)
... 10 more
If required i'll post the pom.xml too. Any sort of help will be highly appreciated.

Error mapping stateless beans with Spring

I have a Java EE application that runs on JBoss 6.4 EAP and uses Spring Security. Apparently all Maven dependencies are mapped. However, at the moment stateless beans are loaded, the following message appears:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'autenticacaoBO': Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: ajg2/AutenticacaoBO -- service jboss.naming.context.java.app."ajg2-0.0.1-SNAPSHOT".ajg2.AutenticacaoBO
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1514) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) [spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
... 26 more
Caused by: javax.naming.NameNotFoundException: ajg2/AutenticacaoBO -- service jboss.naming.context.java.app."ajg2-0.0.1-SNAPSHOT".ajg2.AutenticacaoBO
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:104)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:197)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:174)
at org.jboss.as.naming.InitialContext$DefaultInitialContext.lookup(InitialContext.java:245)
File spring-security.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:sec="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<jee:local-slsb id="autenticacaoBO" jndi-name="java:app/ajg2/AutenticacaoBO" business-interface="br.jus.ajg.bo.IAutenticacaoBO"/>
<bean id="appInternetAuthenticationProvider" class="br.jus.ajg.seguranca.AppInternetAuthenticationProvider">
<property name="autenticacaoBO" ref="autenticacaoBO"/>
</bean>
<bean id="appIntranetAuthenticationProvider" class="br.jus.ajg.seguranca.AppIntranetAuthenticationProvider">
<property name="autenticacaoBO" ref="autenticacaoBO"/>
</bean>
</beans>
File AppInternetAuthenticationProvider.java:
package br.jus.ajg.seguranca;
import java.io.IOException;
import java.io.Serializable;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import br.jus.ajg.bo.IAutenticacaoBO;
import br.jus.ajg.modelo.Profissional;
import br.jus.ajg.util.VerifyRecaptcha;
#Component
public class AppInternetAuthenticationProvider implements AuthenticationProvider, Serializable {
private IAutenticacaoBO autenticacaoBO;
/**
* Este set é usado para injeção do EJB
*/
public void setAutenticacaoBO(IAutenticacaoBO autenticacaoBO) {
this.autenticacaoBO = autenticacaoBO;
}
public AppInternetAuthenticationProvider() {
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!autenticacaoBO.isSistemaEmManutencao()) {
AppWebAuthenticationDetails webAuthDetail = (AppWebAuthenticationDetails) authentication.getDetails();
String gRecaptchaResponse = webAuthDetail.getRecaptcha_response();
boolean validouRecaptcha = false;
try {
validouRecaptcha = VerifyRecaptcha.verify(gRecaptchaResponse);
} catch (IOException e) {
new AuthenticationServiceException("Problema na validação do recaptcha", e);
}
if (validouRecaptcha) {
String login = authentication.getName();
String senha = authentication.getCredentials().toString();
String infoNavegador = ((AppWebAuthenticationDetails) authentication.getDetails()).getHeaderRequest();
Profissional p = autenticacaoBO.getProfissionalBO().autenticaProfissional(login, senha, infoNavegador);
if (p != null) {
return autenticacaoBO.geraTokenProfissional(p, senha);
} else {
throw new AuthenticationServiceException("CPF ou senha inválidos");
}
} else {
throw new AuthenticationServiceException("O desafio reCAPTCHA foi respondido incorretamente!");
}
} else {
throw new AuthenticationServiceException("Sistema em manutenção. Tente mais tarde.");
}
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
Can someone help?
Thanks Pavel. In fact, I forgot a tip sent by the original developer of this project. Just added project libs to the classpath tab of the 'Open laucnh configuration' JBoss option.
JBoss started without errors and app is running fine.

Spring:Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]

I am new new to spring programming.While executing a program for fetching some records from mysql database i am getting these errors:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'jtemplate' while setting bean property 'jdbcTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jtemplate' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'ds' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at Test.main(Test.java:15)
I have three files in my project.
1.EmpDAO.java:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
public class EmpDAO {
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Student> getAllStudents(){
return (List<Student>) template.query("select * from test",new ResultSetExtractor(){
#Override
public List<Student> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Student> list=new ArrayList<Student>();
while(rs.next()){
Student e=new Student();
e.setName(rs.getString(1));
e.setRoll(rs.getString(2));
list.add(e);
}
return list;
}
});
}
}
2.Student.java:
public class Student {
private String name;
private String roll;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public void display(){
System.out.println("Name: "+name+" Roll="+roll);
}
}
3.applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="edao" class="EmpDAO">
<property name="jdbcTemplate" ref="jtemplate"></property>
</bean>
</beans>
4.Test.java(for execution):
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
EmpDAO dao=(EmpDAO)factory.getBean("edao");
List<Student> list=dao.getAllStudents();
for(Student e:list)
System.out.println(e);
}
}
The jars that i included in reference library:
These are the jars i included
Kindly help me in this regards.A prevalentines day thank you is in advance.
The relevant part of your errormessage is:
java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
You can download that jar from here: 5.1.38, or look for different versions on the central nexus repository.
Note: you would be much better of employing some dependency management system, rather than doing this manually. I suggest taking a look at Maven.

custom spring xd module with spring data elasticsearch: No qualifying bean of type [ElasticsearchTemplate] found

I customed a spring xd processor module,try link to elasticsearch in my module with spring data elasticsearch.
unittest is ok,but when deploy in the singlenode, throw the exception:
- Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.
config.TransformerFactoryBean#0': Cannot create inner bean 'com.eheluo.bigdata.wenxin.ToElasticsearch#0' of type [com.eh
eluo.bigdata.wenxin.ToElasticsearch] while setting bean property 'targetObject'; nested exception is org.springframework
.beans.factory.BeanCreationException: Error creating bean with name 'com.eheluo.bigdata.wenxin.ToElasticsearch#0': Injec
tion of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Coul
d not autowire field: private org.springframework.data.elasticsearch.core.ElasticsearchTemplate com.eheluo.bigdata.wenxi
n.ToElasticsearch.elasticsearchTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionExcep
tion: No qualifying bean of type [org.springframework.data.elasticsearch.core.ElasticsearchTemplate] found for dependenc
y: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.spr
ingframework.beans.factory.annotation.Autowired(required=true)}
it can't find bean org.springframework.data.elasticsearch.core.ElasticsearchTemplate.
my pom file is:
<parent>
<groupId>org.springframework.xd</groupId>
<artifactId>spring-xd-module-parent</artifactId>
<version>1.1.1.RELEASE</version>
<relativePath></relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>1.2.1.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
....
my custom module code is :
#Component
public class ToElasticsearch {
private Logger logger = Logger.getLogger(ToElasticsearch.class);
#Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public String process(NewDataInterface data){
NewData newData = new NewData();
BeanUtils.copyProperties(data, newData);
String docid = elasticsearchTemplate.index(genIndexQuery(newData));
logger.debug("save to es");
return docid;
}
my application.properties is :
# options_class=com.eheluo.bigdata.wenxin.ToElasticsearch
# ELASTICSEARCH (ElasticsearchProperties})
# The cluster name (defaults to elasticsearch)
spring.data.elasticsearch.cluster-name=elasticsearch
# The address(es) of the server node (comma-separated; if not specified starts a client node)
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
# if spring data repository support is enabled
spring.data.elasticsearch.repositories.enabled=true
my module.properties has nothing to export options
my module.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
">
<channel id="input"/>
<transformer input-channel="input" output-channel="output">
<beans:bean class="com.eheluo.bigdata.wenxin.ToElasticsearch" />
</transformer>
<channel id="output"/>
</beans:beans>
my unittest is :
public class ToElasticsearchTest {
private static SingleNodeApplication application;
private static int RECEIVE_TIMEOUT = 5000;
private static String moduleName = "toelasticsearch";
#BeforeClass
public static void setUp() {
RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport();
application = new SingleNodeApplication().run();
SingleNodeIntegrationTestSupport singleNodeIntegrationTestSupport = new SingleNodeIntegrationTestSupport(application);
singleNodeIntegrationTestSupport.addModuleRegistry(new SingletonModuleRegistry(ModuleType.processor, moduleName));
}
#Test
public void test() {
String streamName = "toElasticsearchTest";
String newID = UUID.randomUUID().toString();
NewDataInterface newData = new NewDataPOJO();
newData.setsomthing("testtesttest");
newData.setId(newID);
Multiset<String> words = ConcurrentHashMultiset.create();
words.add("1");
words.add("2");
words.add("3");
words.add("4", 2);
newData.setsomthinx(words);
String processingChainUnderTest = moduleName;
SingleNodeProcessingChain chain = chain(application, streamName, processingChainUnderTest);
chain.sendPayload(newData);
String result = (String) chain.receivePayload(RECEIVE_TIMEOUT);
assertEquals(newID, result);
chain.destroy();
}
}
unit test is always ok:Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
but can't work in singlenode rutime.
why it can't find ElasticsearchTemplate in runtime?

Resources