Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource - spring

I am new to Spring. I am creating simple project in which I just call generateOutout() method using beans.
IOutputGenerator Interface:
package mian.java;
public interface IOutputGenerator {
public void generateOutput();
}
CsvOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class CsvOutputGenerator implements IOutputGenerator{
public void generateOutput(){
System.out.println("Csv Output Generator");
}
}
JsonOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class JsonOutputGenerator implements IOutputGenerator {
public void generateOutput(){
System.out.println("Json Output Generator");
}
}
OutputHelper.java:
package mian.java;
public class OutputHelper {
IOutputGenerator outputGeneratorCsv;
IOutputGenerator outputGeneratorJson;
public void generateOutput(){
outputGeneratorCsv.generateOutput();
outputGeneratorJson.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGeneratorCsv,IOutputGenerator outputGeneratorJson){
this.outputGeneratorCsv = outputGeneratorCsv;
this.outputGeneratorJson = outputGeneratorJson;
}
}
AppViaSpring.java (Main class):
package mian.java;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppViaSpring {
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.generateOutput();
}
}
Spring-Common.xml (Bean Class in main.resources package):
<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-2.5.xsd">
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
</bean>
<bean id="CsvOutputGenerator" class="main.java.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="main.java.JsonOutputGenerator" />
</beans>
and Error is :
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource [Spring-Common.xml]; nested exception is java.lang.ClassNotFoundException: main.java.OutputHelper
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1141)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:758)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:422)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at mian.java.AppViaSpring.main(AppViaSpring.java:10)
Caused by: java.lang.ClassNotFoundException: main.java.OutputHelper
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:211)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:385)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1138)
... 9 more

you forgot to add the JsonOutputGenerator bean for OutputHelper
try this:
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
<property name="outputGeneratorJson" ref="JsonOutputGenerator" />
</bean>
note you can also use context.getBean(OutputHelper.class), no casting will be required
edit:
on the further look at the problem. The setter you are using has two arguments which violates javaBean convention. There are few options.
1. You simply pass the map to the setter.
2. Create setter for each generator field.
3. You inject outputGeneratorCsv and outputGeneratorJson in the constructor - i would recommend that. In that case you would have to add constructor with two arguments (like your setter method) and modify the spring context xml to something like that:
<bean id="OutputHelper" class="main.java.OutputHelper">
<constructor-arg ref="outputGeneratorCsv"/>
<constructor-arg ref="outputGeneratorJson"/>
</bean>
here also some more info, why to use constructor injections:
We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).
Setter injection versus constructor injection

Related

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.

Getting Spring #Autowired and #postconstuct work

I am trying to introduce a new bean to existing project
Current bean is
package w.x.y.z.pkgA
#Component
public class BeanA implements InterfaceA {
}
And I am trying to add new Bean to w.x.y.z.pkgB
package w.x.y.z.pkgB
public class BeanB implements InterfaceB {
#Autowired
private BeanA beanA
#PostConstruct
public void postConstructMethod() {
//Call some method in BeanA
}
}
From BeanB I want to access BeanA data and in BeanB post construct I want to register BeanB with BeanA. So I want to call BeanA method
And All these packages are packaged as jar
and spring context xml is
<context:annotation-config />
<context:component-scan base-package="w.x.y.z.pkgA,w.x.y.z.pkgB" />
<bean id="beanb" clas="w.x.y.z.pkgB.BeanB"></bean>
But during deployment I get exception about bean in create state
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'context': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:347)
at w.x.y.z.BeanA<init>(BeanA.java:25)
at w.x.y.z.BeanB.<init>(BeanB.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
I have also tried removed #Autowired and getting the BeanA object using getBeanFactory().getBean(BeanA.class). But I get same error.
If I remove bean entry from xml file them it gets deployed properly but post construct is never called as it is no longer a bean.
BeanA is not dependent on BeanB at all. No references?
Is there a way to get this #Autowired and #PostConstruct to work when 2 beans are in same jar?
You declare the bean as <bean id="beanb" clas="w.x.y.z.BeanB"> from w.x.y.z package.
Try with
package w.x.y.z
#Component
public class BeanA implements InterfaceA {
}
package w.x.y.z
public class BeanB implements InterfaceB {
private BeanA beanA
#PostConstruct
public void postConstructMethod() {
//Call some method in BeanA
}
// Getters and Setters
}
and
<context:annotation-config />
<context:component-scan base-package="w.x.y.z" />
<bean id="beanb" clas="w.x.y.z.BeanB">
<property name="beanA" value="beanA"/> <!-- Spring will create beanA as it is annotated with #Component -->
</bean>

Spring Transactional annotation giving CGLIB error

I am getting the following error when using the #Transactional annotation. Any ideas?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRepository' defined in file [myFile]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class myRepository]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:636)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at myRepository.main(myRepository.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class myRepository]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:217)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:111)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:477)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:409)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1520)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
... 16 more
Caused by: java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.cglib.proxy.Enhancer.emitConstructors(Enhancer.java:721)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:499)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.create(Enhancer.java:285)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205)
Code:
#Repository
public class MyRepository {
private MyDao myDao;
#Autowired
public MyRepository(MyDao myDao) {
this.myDao = myDao
}
#Transactional
public void save(Object obj) {
if (obj.isNew())
myDao.create(obj)
}
}
XML:
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- Enable Annotation based Declarative Transaction Management -->
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
<!-- Creating TransactionManager Bean, since JDBC we are creating of type DataSourceTransactionManager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" >
// datasource settings
</bean>
Superclass has no null constructors but no arguments were given
You need to autowire the field, and either remove the constructor or provide an additional no-argument constructor.
#Repository
public class MyRepository {
#Autowired
private MyDao myDao;
#Transactional
public void save(Object obj) {
if (obj.isNew())
myDao.create(obj)
}
}
}
Alternatively, use a #Transactional interface instead of a class so CGLIB doesn't need to be involved at all.
#Repository
#Transactional
public interface MyRepository {
void save(Object obj);
}
public class MyRepositoryImpl implements MyRepository {
private final MyDao myDao;
#Autowired
public MyRepository(MyDao myDao) {
this.myDao = myDao
}
public void save(Object obj) {
if (obj.isNew())
myDao.create(obj)
}
}
}

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.

Spring constructor dependency Injection Issues

I have 2 classes
public class Abcd{
private String username;
private String password;
public Abcd(#Value("${username}") String userName, #Value("${password}") String password) {
...
}
public String retrieveValues(){
......
return "someString";
}
}
public class SomeClass{
#Autowired
private Abcd obj;
public String method1(){
obj.retrieveValues();
}
I have a Xml as below.
<context:annotation-config />
<context:property-placeholder location="classpath:applNew.properties" />
<bean id="abcd" class="com.somecompany.Abcd">
<constructor-arg type="java.lang.String" value="${prop.user}" />
<constructor-arg type="java.lang.String" value="${prop.password}" />
</bean>
<bean id="someclass"
class="com.differentcompany.SomeClass">
</bean>
When I build the project and start the server, i see the below exceptions.
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'abcd' defined in URL []: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class []: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
Caused by: java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
I dont understand what could be the issue to do a constructor injecting this way. Is there any solution for this?
Classes to be proxied by CGLIB (for AOP support) must have no-args constructors.
These no-args constructors don't have to be public and it doesn't affect anything else - you can use other constructors as usually:
public class Abcd{
// Dummy constructor for AOP
Abcd() {}
public Abcd(#Value("${username}") String userName, #Value("${password}") String password) { ... }
...
}
See also:
7.6 Proxying mechanisms

Resources