I have a problem with a realization of Spring in Action example of a programme.
Test class:
#Test
public void testBasicUsage() throws PerformanceException {
ApplicationContext context = new ClassPathXmlApplicationContext("/**/java/springidol/spring-idol.xml");
Performer performer = (Performer) context.getBean("juggler");
performer.perform();
}
Juggler class that should be configured by Spring
public class Juggler implements Performer {
private int beanBags = 3;
public Juggler() {
}
public Juggler(int beanBags) {
this.beanBags = beanBags;
}
#Override
public void perform() throws PerformanceException {
System.out.println("JUGGLING " + beanBags + " BEANBAGS");
}
}
And xml configuration file for this bean:
<?xml version="1.0" encoding="UTF-8"?>
<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="juggler"
class="springidol.Juggler">
<constructor-arg value="15"/>
</bean>
</beans>
this code throw NoSuchBeanDefinitionException:
Aug 30, 2018 1:20:43 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1c53fd30: startup date [Thu Aug 30 13:20:43 EEST 2018]; root of context hierarchy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'juggler' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:686)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
at springidol.TestMain.testBasicUsage(TestMain.java:12)
I think the class-path you provided in ClassPathXmlApplicationContextshould be where the XML configuration in present. The files on classpaths are automatically scanned, we just need to provide folder paths.
Try below in Test class with changes:
ApplicationContext context = new ClassPathXmlApplicationContext("java/springidol/spring-idol.xml");
Reference: Spring Source
Related
This question already has an answer here:
What is a NoSuchBeanDefinitionException and how do I fix it?
(1 answer)
Closed 5 years ago.
I am trying an example to connect to database using jdbc and spring and getting the below exception. Please advise.
exception:
Aug 17, 2017 10:44:51 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#6422b8ff: startup date [Thu Aug 17 22:44:51 IST 2017]; root of context hierarchy
Aug 17, 2017 10:44:51 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'daoClass' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:979)
at org.manjosh.main.JdbcMain.main(JdbcMain.java:14)
main class:
package org.manjosh.main;
import org.manjosh.dao.DaoClass;
import org.manjosh.model.Circle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JdbcMain {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
DaoClass dao = ctx.getBean("daoClass",DaoClass.class);
Circle circle = dao.getCirle(1);
System.out.println(circle.getName());
}
}
dao class:
package org.manjosh.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.manjosh.model.Circle;
import org.springframework.stereotype.Component;
#Component
public class DaoClass {
public Circle getCirle(int circleId){
String driver = "oracle.jdbc.driver.OracleDriver";
Connection conn = null;
try{
//step1 load the driver class
Class.forName(driver).newInstance();
//step2 create the connection object
conn =DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","system");
//step3 create the statement object
PreparedStatement stmt=conn.prepareStatement("SELECT * FROM circle where ID =?");
stmt.setInt(1, circleId);
Circle circle = null;
//step4 execute query
ResultSet rs=stmt.executeQuery();
while(rs.next()){
circle = new Circle(rs.getInt(circleId),rs.getString("name"));
}
rs.close();
stmt.close();
return circle;
}
catch(Exception e){
throw new RuntimeException(e);
}
finally {
try{
conn.close();
}
catch(SQLException e){}
}
}
}
spring 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"
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">
<context:annotation-config/>
<context:component-scan base-package = "org.manjosh.main"/>
</beans>
In spring.xml, you have defined component scan configuration as <context:component-scan base-package = "org.manjosh.main"/> which will scan all classes under org.manjosh.main. As your DaoClass is in org.manjosh.dao, spring will not create bean of DaoClass hence exception NoSuchBeanDefinitionException is thrown.
Change <context:component-scan base-package = "org.manjosh.main"/> to <context:component-scan base-package = "org.manjosh.main,org.manjosh.main"/>
<context:component-scan> scans packages to find and register beans within the application context.
To resolve NoSuchBeanDefinitionException issue please make below change in
spring.xml file
Replace
<context:component-scan base-package = "org.manjosh.main"/>
with
<context:component-scan base-package = "org.manjosh.dao,org.manjosh.main"/>
OR
<context:component-scan base-package = "org.manjosh.dao"/>
OR
<context:component-scan base-package = "org.manjosh.*"/>
OR
<context:component-scan base-package = "*"/>
Spring configuration 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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" >
<!-- Enable AspectJ style of Spring AOP -->
<aop:aspectj-autoproxy />
<bean id="studService" class="springAOP.Student">
<property name="age" value="20"></property>
<property name="name" value="Sangeetha"></property>
</bean>
<bean id="logging" class="springAOP.Logging"/>
<aop:config>
<aop:aspect id="log" ref="logging" >
<aop:pointcut id="student" expression="execution(* springAOP.Student.*(..))" />
<!-- before advice definition -->
<aop:before pointcut-ref="student" method="beforeAdvice"/>
<!-- after advice definition -->
<aop:after pointcut-ref="student" method="afterAdvice"/>
<!-- after-returning advice -->
<aop:after-returning pointcut-ref="student" method="afterReturningAdvice" returning="retVal"/>
<!-- after throwing advice -->
<aop:after-throwing pointcut-ref="student" method="afterThrowingAdvice" throwing="ex"/>
<!-- around advice -->
<aop:around pointcut-ref="student" method="aroundAdvice"/>
</aop:aspect>
</aop:config>
Application class
package spring;
import springAOP.Student;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringApp {
private AbstractApplicationContext context;
HelloWorld obj;
Student student;
public SpringApp()
{
context = new ClassPathXmlApplicationContext("spring-beans.xml");
}
public void initializeBeans(){
obj = (HelloWorld)context.getBean("sayHello");
student = (Student)context.getBean("studService");
}
public static void main(String args[]){
SpringApp app = new SpringApp();
app.initializeBeans();
System.out.println(" getting name and age");
Student stud = (Student)app.context.getBean("studService");
stud.getName();
stud.getAge();
}
EntityClass
package springAOP;
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
System.out.println("Setting Age : " + age);
}
public Integer getAge() {
System.out.println("Age : " + age);
return age;
}
public void setName(String name) {
this.name = name;
System.out.println("Setting Name : " + name);
}
public String getName() {
System.out.println("Name : " + name);
return name;
}
public void printThrowException() {
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
Output:
Jul 17, 2015 9:51:50 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#ad9418: startup date [Fri Jul 17 21:51:50 IST 2015]; root of context hierarchy
Jul 17, 2015 9:51:51 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-beans.xml]
Jul 17, 2015 9:51:52 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#e2abd: defining beans [org.springframework.aop.config.internalAutoProxyCreator,studService,logging,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,org.springframework.aop.aspectj.AspectJPointcutAdvisor#4,student,employee,employeeService,dataSource,sayHello,spellCheck]; root of factory hierarchy
Setting Age : 20
Setting Name : Sangeetha
Jul 17, 2015 9:51:53 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: oracle.jdbc.driver.OracleDriver
Setting Message is : you are in spring Hello World
i m in init
i 2 j 3
Going to setup student profile.
After smooth execution
Returning:null
Student profile has been setup.
Going to setup student profile.
After smooth execution
Returning:null ==> returning NULL
Student profile has been setup.
Logging.java:
package springAOP;
public class Logging {
/**
* * This is the method which I would like to execute * before a selected
* method execution.
*/
public void beforeAdvice() {
System.out.println("Going to setup student profile.");
}
/**
* * This is the method which I would like to execute * after a selected
* method execution.
*/
public void afterAdvice() {
System.out.println("Student profile has been setup.");
}
/**
* * This is the method which I would like to execute * when any method
* returns.
*/
public void afterReturningAdvice(String retVal) {
System.out.println("Returning:" + retVal);
}
/**
* * This is the method which I would like to execute * if there is an
* exception raised.
*/
public void afterThrowingAdvice(IllegalArgumentException ex) {
System.out.println("There has been an exception: " + ex.toString());
}
public void aroundAdvice(){
System.out.println("After smooth execution " );
}
}
Issue:
When the getName and getAge methods are accessed, afterReturning is not getting retValue, value is passed as NULL. Kindly help me to understand why value is passed as NULL
You can use the ProceedingJoinPoint of aspectJ.
public void afterReturningAdvice(ProceedingJoinPoint joinpoint) {
Object[] args = joinpoint.getArgs()
Object retVal = null;
if(args.length > 0) {
retVal = args[0];
}
System.out.println("Returning:" + retVal);
}
Whoever answers correct will be rewarded
My Implementation is as follows:
NextShipmentDaoImpl.java
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
LoginController.java
#Controller
public class LoginController {
#Autowired
private NextShipmentDao nextShipmentDao;
public void setNextShipmentDao(NextShipmentDao nextShipmentDao) {
this.nextShipmentDao = nextShipmentDao;
}
While Creating the required above bean like this:
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
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: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-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/board" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<security:http auto-config="true" >
<security:intercept-url pattern="/index*" access="ROLE_USER" />
<security:form-login login-page="/login.htm" default-target-url="/index.htm"
authentication-failure-url="/loginerror.htm" />
<security:logout logout-success-url="/logout.htm" />
</security:http>
<context:component-scan base-package="com.ibrahim.controller,com.ibrahim.domain,com.ibrahim.dao" />
<bean id="jspViewResolver" 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>
</beans>
Everything works fine. But when I try to create a bean This shows the error
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 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ibrahim.dao.NextShipmentDao com.ibrahim.controller.LoginController.nextShipmentDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nextShipmentDao' defined in ServletContext resource [/WEB-INF/board-dao.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
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:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4728)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5166)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ibrahim.dao.NextShipmentDao com.ibrahim.controller.LoginController.nextShipmentDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nextShipmentDao' defined in ServletContext resource [/WEB-INF/board-dao.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 22 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nextShipmentDao' defined in ServletContext resource [/WEB-INF/board-dao.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
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.findAutowireCandidates(DefaultListableBeanFactory.java:912)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 24 more
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000)
... 35 more
Caused by: java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134)
at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:165)
at com.ibrahim.dao.NextShipmentDaoImpl.<init>(NextShipmentDaoImpl.java:28)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 37 more
May 07, 2015 12:21:48 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
May 07, 2015 12:21:48 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/13.1SecuringUrlAcces] startup failed due to previous errors
May 07, 2015 12:21:48 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
May 07, 2015 12:21:48 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
May 07, 2015 12:21:48 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
May 07, 2015 12:21:48 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 12402 ms
Here's My NextShipmentDaoImpl.java
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
JdbcTemplate jdbcTemplate= new JdbcTemplate(dataSource);
#Override
public List<NextShipment> display() {
String sql = "SELECT * FROM NEXTSHIPMENT";
List<NextShipment> shipments = new ArrayList<NextShipment>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
for (Map row : rows) {
NextShipment shipment = new NextShipment();
shipment.setOid((String) row.get("OID"));
shipment.setAddress((String) row.get("ADDRESS"));
shipment.setPack_Date((Date) row.get("PACK_DATE"));
shipment.setIsAvailable((Boolean) row.get("ISAVAILABLE"));
shipment.setAssignShipper((String) row.get("ASSIGNSHIPPER"));
shipment.setInTransit((Boolean) row.get("InTransit"));
shipments.add(shipment);
}
return shipments;
}
}
The times of the XML-based configuration are over.
I strongly recommend you to use Annotated Configuration
Something like this:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "com.myapp.*")
public class AppConfiguration extends WebMvcConfigurerAdapter {
#Bean
public DataSource myDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("<full.driver.class.name>");
dataSource.setUrl("url");
dataSource.setUsername("dit");
dataSource.setPassword("pass");
return dataSource;
}
[...] other Beans like TransactionManager....
}
The stacktrace says :
you correctly autowire nextShipmentDAO in loginController
but dataSource property is null is the NextShipmentDAOImpl bean
and the exception occurs in JdbcTemplate initialization
The NextShipmentDAOImpl gives the cause : you correctly inject the datasource, but initialize the JdbcTemplate at construction time. So here is what happens :
jvm creates a NextShipmentDaoImpl object
jvm initializes all fields of the object including jdbcTemplate
spring sets the datasource field ... too late !
[It had been noted in comments by #M.Deinum, but I did not give it enough attention]
You shall never use an injected field at creation time, because at that moment it has not been injected. You should instead use an initialization method called by spring after all properties have been set :
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
JdbcTemplate jdbcTemplate;
void init(void) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
and declare the bean that way :
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl"
init-method="init">
<property name="dataSource" ref="dataSource"></property>
</bean>
NextShipmentDaoImpl.java looks like this
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
JdbcTemplate jdbcTemplate;
public NextShipmentDaoImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
In the above lines of code I had declared JdbcTemplate inside its implementation function itself. Where it is used.
And the relevant bean I had declared is:
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
LoginController remains the same:
#Controller
public class LoginController {
#Autowired
private NextShipmentDao nextShipmentDao;
public void setNextShipmentDao(NextShipmentDao nextShipmentDao) {
this.nextShipmentDao = nextShipmentDao;
}
I had shifted my spring and spring security jars from 3.2.4 to 3.2.7
Problem got solved in this manner.
I'm trying to find out what have I done wrong. It would be great if anyone could help me. I keep getting this in an infinite loop:
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#799f7e29: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#548a9f61: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
UsersDAOImp :
public class UsersDAOImp extends GenericEntityDAO implements UsersDAO {
private SessionFactory sessionFactory = (SessionFactory) BeanManager.getBean("sessionFactory");
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Users> selectAll() {
Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Users.class);
List<Users> users = (List<Users>) criteria.list();
session.getTransaction().commit();
return users;
}
}
UsersService
public class UsersService {
UsersDAOImp usersDAO = new UsersDAOImp();
public void setUsersDAO(UsersDAOImp usersDAO) {
this.usersDAO = usersDAO;
}
public UsersDAOImp getUsersDAO() {
return usersDAO;
}
public List<Users> getAllUsers() {
return getUsersDAO().selectAll();
}
}
Bean manager used to get context
public class BeanManager {
/* BeanManager is used to parse Beans.xml file */
private static ApplicationContext context;
private BeanManager() {
}
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
BeanManager.context = context;
}
public static Object getBean(String beanId) {
if (context == null) {
context = new ClassPathXmlApplicationContext("Beans.xml");
}
Object result = context.getBean(beanId);
return result;
}
}
This is my 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: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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="usersDAO" class="com.survey.persistance.DAO.UsersDAOImp" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/app" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>
I am facing the following error when I try to create bean using Application Context for the circle class! Circle class implements the Shape interface which contains a method draw().
Configuration:
I am learning spring and have setup a Java Project in eclipse with all the required jars (Spring and Apache commons logging). I have the spring.xml in my classpath in the src folder. Have also tried downloading the latest jars (Spring 4.0.4 release, previously worked with 4.0.0) but now is not working. Cannot think of any solution to fix this.
Error:
May 11, 2014 6:20:50 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#90832e: startup date [Sun May 11 18:20:50 EDT 2014]; root of context hierarchy
May 11, 2014 6:20:50 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor': Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:88)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.springApplication.DrawingApplication.main(DrawingApplication.java:16)
Caused by: java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1071)
... 13 more
Caused by: java.lang.NullPointerException
at org.springframework.beans.PropertyEditorRegistrySupport.<clinit>(PropertyEditorRegistrySupport.java:92)
... 14 more
DrawingApplication.java
package com.springApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApplication {
public static void main(String[] args) {
//The beanFactory reads from an XML file
//BeanFactory context = new XmlBeanFactory(new FileSystemResource("spring.xml"));
//Application Context provides -- Event notification and more than Bean Factory
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//Here we pass the id of the bean from the XML given in the above line
Shape shape = (Shape)context.getBean("circle");
//Calling the draw method through object local object created using Spring
shape.draw();
}
}
Circle.java
package com.springApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Circle implements Shape{
private Point center;
public Point getCenter() {
return center;
}
#Autowired
#Qualifier("circleRelated")
public void setCenter(Point center) {
this.center = center;
}
#Override
public void draw() {
System.out.println("Drawing a Circle");
System.out.println("Center Point is: (" + center.getX() + ", " + center.getY() + ")");
}
}
Point.java
package com.springApplication;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
spring.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"
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">
<bean id="pointA" class="com.springApplication.Point">
<qualifier value="circleRelated" />
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>
<bean id="PointB" class="com.springApplication.Point">
<property name="x" value="0"/>
<property name="y" value="20"/>
</bean>
<bean id="PointC" class="com.springApplication.Point">
<property name="x" value="-20"/>
<property name="y" value="0"/>
</bean>
<bean id="circle" class="com.springApplication.Circle">
</bean>
<!-- <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> -->
<context:annotation-config/>
</beans>
Please let me know if anything else is needed. Someone please help !
Sorry about the wrong placing!!
#Andrei Stefan
List of Jars ---------
commons-logging-1.1.3
spring-aop-4.0.4.RELEASE
spring-aop-4.0.4.RELEASE-javadoc
spring-aop-4.0.4.RELEASE-sources
spring-aspects-4.0.4.RELEASE
spring-aspects-4.0.4.RELEASE-javadoc
spring-aspects-4.0.4.RELEASE-sources
spring-beans-4.0.4.RELEASE
spring-beans-4.0.4.RELEASE-javadoc
spring-beans-4.0.4.RELEASE-sources
spring-build-src-4.0.4.RELEASE
spring-context-4.0.4.RELEASE
spring-context-4.0.4.RELEASE-javadoc
spring-context-4.0.4.RELEASE-sources
spring-context-support-4.0.4.RELEASE
spring-context-support-4.0.4.RELEASE-javadoc
spring-context-support-4.0.4.RELEASE-sources
spring-core-4.0.4.RELEASE
spring-core-4.0.4.RELEASE-javadoc
spring-core-4.0.4.RELEASE-sources
spring-expression-4.0.4.RELEASE
spring-expression-4.0.4.RELEASE-javadoc
spring-expression-4.0.4.RELEASE-sources
spring-framework-bom-4.0.4.RELEASE
spring-framework-bom-4.0.4.RELEASE-javadoc
spring-framework-bom-4.0.4.RELEASE-sources
spring-instrument-4.0.4.RELEASE
spring-instrument-4.0.4.RELEASE-javadoc
spring-instrument-4.0.4.RELEASE-sources
spring-instrument-tomcat-4.0.4.RELEASE
spring-instrument-tomcat-4.0.4.RELEASE-javadoc
spring-instrument-tomcat-4.0.4.RELEASE-sources
spring-jdbc-4.0.4.RELEASE
spring-jdbc-4.0.4.RELEASE-javadoc
spring-jdbc-4.0.4.RELEASE-sources
spring-jms-4.0.4.RELEASE
spring-jms-4.0.4.RELEASE-javadoc
spring-jms-4.0.4.RELEASE-sources
spring-messaging-4.0.4.RELEASE
spring-messaging-4.0.4.RELEASE-javadoc
spring-messaging-4.0.4.RELEASE-sources
spring-orm-4.0.4.RELEASE
spring-orm-4.0.4.RELEASE-javadoc
spring-orm-4.0.4.RELEASE-sources
spring-oxm-4.0.4.RELEASE
spring-oxm-4.0.4.RELEASE-javadoc
spring-oxm-4.0.4.RELEASE-sources
spring-test-4.0.4.RELEASE
spring-test-4.0.4.RELEASE-javadoc
spring-test-4.0.4.RELEASE-sources
spring-tx-4.0.4.RELEASE
spring-tx-4.0.4.RELEASE-javadoc
spring-tx-4.0.4.RELEASE-sources
spring-web-4.0.4.RELEASE
spring-web-4.0.4.RELEASE-javadoc
spring-web-4.0.4.RELEASE-sources
spring-webmvc-4.0.4.RELEASE
spring-webmvc-4.0.4.RELEASE-javadoc
spring-webmvc-4.0.4.RELEASE-sources
spring-webmvc-portlet-4.0.4.RELEASE
spring-webmvc-portlet-4.0.4.RELEASE-javadoc
spring-webmvc-portlet-4.0.4.RELEASE-sources
spring-websocket-4.0.4.RELEASE
spring-websocket-4.0.4.RELEASE-javadoc
spring-websocket-4.0.4.RELEASE-sources
All of these plus other default system libraries are referenced.
The problem occurs because
PropertyEditorRegistrySupport.class.getClassLoader()
is null. According to JavaDoc, this happens if the class PropertyEditorRegistrySupport has been loaded by the bootstrap class loader instead of the system class loader:
Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.
Perhaps your Spring libraries are on the endorsed class path?