2017-02-07 1 views
1

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>에서 값을 사용합니다 어떤 순서로 알아낼 수 아니에요.

+1

가능한 경우 XML 기반 구성을 피하십시오. –

+0

@BoristheSpider 왜 BTW입니까? – Andremoniy

+1

@Andremoniy은 스프링 커뮤니티가 XML 기반 구성에서 멀어지고 있다고 생각합니다. 주된 이유는, 필자가 볼 수있는 한, 자바 기반의 설정은 훨씬 더 많은 컴파일 타임 타입 안전을 추가하기 때문에 더 강력합니다. 이것은 JavaEE의 이동을'web.xml '등에서 컨벤션 오버 구성과 메타 데이터 기반 컨피규레이션의 조합으로 미러링합니다. –

답변

2

짧은 대답 : 클래스 생성자에서 설명한 순서대로 인수가 필요합니다.

증명 Spring docs (p.7.4.1)에서 :

생성자 인자 분석 대응 (matching)은 인자의 유형을 사용하여 발생합니다. 생성자 인수 의 빈 정의에 잠재적 인 모호성이 없으면 생성자 인수 이 빈 정의에 정의 된 순서는 콩이 일 때 해당 생성자에 인수가 제공되는 순서입니다 인스턴스화.

+0

이제' '값을 서로 바꿔서 사용할 때 타입 불일치가 발생했다고 생각했습니다. – Chip

0

This post 내 질문에 대한 답변을 작성하는 데 도움이되었습니다.

public Triangle(String type, int height) { 
     this.type = type; 
     this.height = height; 
    } 

걸리는,

  • type (인스턴스 변수) 형 String의 첫번째 인수하고, 두 번째 인수 int
  • height로서 :

    이 내 생성자이다.

따라서 spring.xml 파일에서 우리가 제공하는 값은 <constructor-arg>이며 클래스의 생성자와 동일한 순서 여야합니다. 그래서이 줄을 사용하려고 시도했을 때 예외가 발생했습니다.

<constructor-arg value = "20" /> 
<constructor-arg value = "Isosceles"/> 

이유는,

  • 먼저 인수 "20"이 될 것이다 문자열로 취하고 type 인스턴스 변수를 설정한다.두 번째 인자 'Isosceles'(AN int 변환 String) 타입 불일치
  • height 인스턴스 변수 일어난다.
1


는 클래스 생성자의 같은 순서로 <constructor-args>을 쓸 수 있습니다, 당신과 함께 동의합니다. 당신은 또한 아래 <constructor-args>에 인덱스를 지정할 수 있습니다

<constructor-arg index = "0" value = "Equilateral"></constructor-arg> 
<constructor-arg index = "1" value= "20"></constructor-arg> 

그래서 여기에 index은 당신이 그들의 매개 변수의 순서에 따라 여러 생성자 사이에 해결하려면 사용할 수 있습니다.
은 그래서 두 개의 인수

  • 첫 번째 인수로 생성자를 위해 모양은 index = "0"type = Equilateral과에 "등변"로 설정됩니다.

  • 두 번째 인수는 index="1"height= 20으로 ""으로 설정됩니다.

    <constructor-arg index = "1" value= "20"></constructor-arg>  
    <constructor-arg index = "0" value = "Equilateral"></constructor-arg> 
    

    프로그램이 예외없이 실행합니다 :


당신은 또한 당신의 다음 <constructor-args>로를 교환 할 수 있습니다.

관련 문제