DI의 생성자 주입을 시도했습니다. type
을 <constructor-arg>
에 지정하지 않은 경우에도이 코드 조각은 정상적으로 작동합니다.Spring은 constructor-args의 값을 어떤 순서로 사용합니까?
삼각형 클래스 :
public class Triangle {
private String type;
private int height;
public Triangle(int height) {
this.height = height;
}
public Triangle(String type, int height) {
this.type = type;
this.height = height;
}
public Triangle(String type) {
this.type = type;
}
public void draw(){
System.out.println(getType()+ " Triangle drawn with height = "+getHeight());
}
public String getType() {
return type;
}
public int getHeight() {
return height;
}
}
구성 파일, spring.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id = "triangle" class = "model.Triangle">
<constructor-arg value = "Isosceles"/>
<constructor-arg value = "20" />
</bean>
</beans>
드라이버 클래스 (main
방법) :
public class Driver {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle) context.getBean("triangle");
triangle.draw();
}
}
그러나, 나는의 라인을 시도 동등하게 spring.xml
에서 <constructor-arg>
, 예외 w 다음과 같이 발생과 같이
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'triangle' defined in class path resource [spring.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
을 나는 봄는 <constructor-arg>
에서 값을 사용합니다 어떤 순서로 알아낼 수 아니에요.
가능한 경우 XML 기반 구성을 피하십시오. –
@BoristheSpider 왜 BTW입니까? – Andremoniy
@Andremoniy은 스프링 커뮤니티가 XML 기반 구성에서 멀어지고 있다고 생각합니다. 주된 이유는, 필자가 볼 수있는 한, 자바 기반의 설정은 훨씬 더 많은 컴파일 타임 타입 안전을 추가하기 때문에 더 강력합니다. 이것은 JavaEE의 이동을'web.xml '등에서 컨벤션 오버 구성과 메타 데이터 기반 컨피규레이션의 조합으로 미러링합니다. –