#java #spring #spring-mvc
#java #spring #spring-mvc
Вопрос:
Привет, я новичок в spring framework, я пробовал пример, показанный в видеороликах в java brains, я столкнулся с некоторой проблемой при попытке выполнить внедрение конструктора, ошибка, похоже, связана с поиском конструктора по умолчанию. ошибка приведена ниже
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'triangle' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [test.Triangle]: No default constructor found; nested exception is java.lang.NoSuchMethodException: test.Triangle.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:965)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911)
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:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.app.main(app.java:18)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [test.Triangle]: No default constructor found; nested exception is java.lang.NoSuchMethodException: test.Triangle.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:70)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:958)
... 13 more
Caused by: java.lang.NoSuchMethodException: test.Triangle.<init>()
at java.lang.Class.getConstructor0(Class.java:2721)
at java.lang.Class.getDeclaredConstructor(Class.java:2002)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:65)
... 14 more
Мой 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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="triangle" class="test.Triangle">
<constructor-arg value="Right"/>
</bean>
Основной класс
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class app {
public static void main(String args[]) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle obj = (Triangle) context.getBean("triangle");
obj.draw();
}
}
Класс Triangle
package test;
public class Triangle {
private String type;
public Triangle(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void draw(){
System.out.println(getType() " Triangle Drawn of height: ");
}
}
Комментарии:
1. Что-то запускает создание экземпляра класса Triangle без параметра. Вы уверены, что показанная вами конфигурация Spring является единственной в проекте?
2. является
spring.xml
допустимым XML-файлом? есть ли</beans>
тег в конце?3. Спасибо, Йенс Шаудер, это была проблема … я просто скопировал вставленный файл изначально в папку src
Ответ №1:
Проблема в моем случае заключалась в том, что я скопировал вставленный spring.xml в 2 местах, как только для пробной версии, и забыл об этом, отсюда и проблема с созданием экземпляров. ПОЭТОМУ проверьте, находится ли один и тот же файл в разных местах внутри папки проекта.