Method Injection is used for singleton-scoped bean to acquire a new instance of the prototype-scoped bean as explained here
While trying this, I got NullPointerException. Please find below the code.
I am using Spring 3.0.
spring-context.xml
College.javaCode:<bean id="student" class="com.spring.demo.Student" scope="prototype" /> <bean id="college" class="com.spring.demo.College" scope="singleton" p:student-ref="student" />
Student.javaCode:public class College implements ApplicationContextAware { private ApplicationContext applicationContext; private Student student; public void setStudent(Student student) { this.student = applicationContext.getBean("student", Student.class); } public Student getStudent() { return student; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
test code:Code:public class Student { public Student() { System.out.println("Student constructor..."); } }
I am getting below exception on running test code:Code:ConfigurableApplicationContext appContext = new ClassPathXmlApplicationContext( "/spring-context.xml"); College col = appContext.getBean("college", College.class); col = appContext.getBean("college", College.class);
Code:Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'college' defined in class path resource [scope-context.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are: PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'student' threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1363)Student constructor... at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)


Reply With Quote