복붙노트

[SPRING] 봄 IDREF 사용법

SPRING

봄 IDREF 사용법

아래에 정의 된 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="org.tutorial.spring.Triangle">
    <property name="pointA">
        <idref bean="pointA"/>
    </property>
    <property name="pointB" ref="pointB"/>
    <property name="pointC" ref="pointC"/>
</bean>
<bean id="pointA" class="org.tutorial.spring.Point">
    <property name="x" value="0"/>
    <property name="y" value="0"/>
</bean>
<bean id="pointB" class="org.tutorial.spring.Point">
    <property name="x" value="100"/>
    <property name="y" value="200"/>
</bean>
<bean id="pointC" class="org.tutorial.spring.Point">
    <property name="x" value="-100"/>
    <property name="y" value="-200"/>
</bean>
</beans>

Point 클래스는 기본적으로 2 개의 private int 멤버가있는 클래스입니다. 내 문제는 아래 IDREF에 대한 오류가 나타납니다.

Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'org.tutorial.spring.Point' for property 'pointA'; 
nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.tutorial.spring.Point] for property 'pointA': no matching editors or conversion strategy found

내가 아는 한 IDREF (위의 경우)의 목적은 Bean PointA가 Bean 삼각형에 존재 (오류 검사)합니다. 그래서 IDREF 요소에 빈 PointA (문자열)의 이름을 제공했습니다. 위의 오류가 발생하는 이유는 무엇입니까? 왜 그냥 이름을 제공하여 콩 (PointA)의 존재를 확인하고 있다고 생각했을 때 문자열을 Point로 변환하려고합니까?

나는 정말로 혼란 스럽다. 도와주세요. 감사.

해결법

  1. ==============================

    1.idref는 bean (즉 String)의 이름 (식별자)을 전달하는 데 사용됩니다.

    idref는 bean (즉 String)의 이름 (식별자)을 전달하는 데 사용됩니다.

    는 bean이 정의되지 않은 경우 Spring이 불평한다는 점을 제외하고는 문자열 값 pointS와 정확히 동일합니다.

    자세한 내용은 Spring 설명서를 참조하십시오.

    실제 bean을 전달하기 위해서는 pointB와 pointC에서와 마찬가지로 ref를 사용하면된다.

  2. ==============================

    2.idref 요소는 컨테이너에있는 다른 bean의 id (문자열 값 - 참조가 아님)를 a 또는 요소로 전달하는 오류를 방지하는 방법 일뿐입니다.

    idref 요소는 컨테이너에있는 다른 bean의 id (문자열 값 - 참조가 아님)를 a 또는 요소로 전달하는 오류를 방지하는 방법 일뿐입니다.

    idref 요소는 문자열 값을 전달하는 데 사용되며 idref 태그를 사용하면 컨테이너가 전개시 참조 된 명명 된 bean이 실제로 존재하는지 유효성을 확인할 수 있습니다.

    아래의 예를 고려해보십시오.

    secondBean.getSecondMessage ()를 호출 할 때 콘솔의 출력을 확인하십시오.이 값은 idref 속성을 사용하여 설정 한 firstBean입니다.

    노트:      엘리먼트가 가치있는 곳은 ProxyFactoryBean 빈 정의에서 AOP 인터셉터의 설정이다. 인터셉터 이름을 지정할 때 요소를 사용하면 인터셉터 ID의 철자가 잘못 쓰는 것을 방지 할 수 있습니다.

  3. ==============================

    3.'idref'태그를 사용하면 참조 된 명명 된 bean이 실제로 존재하는지 여부를 전개시에 확인할 수 있습니다.

    'idref'태그를 사용하면 참조 된 명명 된 bean이 실제로 존재하는지 여부를 전개시에 확인할 수 있습니다.

    예를 들어,

    <bean id="paulo" class="com.sample.pojo.Author">
        <property name="firstName" value="Paulo" />
        <property name="lastName" value="Coelho" />
        <property name="dateOfBirth" value="24 August 1947" />
        <property name="country" value="India" />
    </bean>
    

    아래와 같이 유효성 검사기 빈을 정의하면 Spring은 배포시 ids osho와 Paulo로 빈의 유효성을 검사합니다. 구성 파일에서 bean을 찾을 수 없으면 Spring은 BeanDefinitionStoreException을 발생시킵니다.

    <bean id="validatorBean" class="com.sample.test.BeansValidator">
        <property name="author1">
            <idref bean="osho" />
        </property>
    
        <property name="author2">
            <idref bean="paulo" />
        </property>
    </bean>
    

    다음은 완전한 작업 응용 프로그램입니다.

    package com.sample.pojo;
    
    public class Author {
        private String firstName;
        private String lastName;
        private String dateOfBirth;
        private String country;
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        public String getDateOfBirth() {
            return dateOfBirth;
        }
    
        public void setDateOfBirth(String dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
        }
    
        public String getCountry() {
            return country;
        }
    
        public void setCountry(String country) {
            this.country = country;
        }
    
        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
                    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
            return builder.toString();
        }
    
    }
    

    BeansValidator.java

    package com.sample.test;
    
        public class BeansValidator {
            private String author1;
            private String author2;
    
            public String getAuthor1() {
                return author1;
            }
    
            public void setAuthor1(String author1) {
                this.author1 = author1;
            }
    
            public String getAuthor2() {
                return author2;
            }
    
            public void setAuthor2(String author2) {
                this.author2 = author2;
            }
    
        }
    

    myConfiguration.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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
        <bean id="osho" class="com.sample.pojo.Author">
            <property name="firstName" value="Osho" />
            <property name="lastName" value="Jain" />
            <property name="dateOfBirth" value="11 December 1931" />
            <property name="country" value="India" />
        </bean>
    
        <bean id="paulo" class="com.sample.pojo.Author">
            <property name="firstName" value="Paulo" />
            <property name="lastName" value="Coelho" />
            <property name="dateOfBirth" value="24 August 1947" />
            <property name="country" value="India" />
        </bean>
    
        <bean id="validatorBean" class="com.sample.test.BeansValidator">
            <property name="author1">
                <idref bean="osho" />
            </property>
    
            <property name="author2">
                <idref bean="paulo" />
            </property>
        </bean>
    
    </beans>
    

    Hello World.java를 실행하면 예외가 발생하지 않습니다.

    package com.sample.test;
    
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;
    
        public class HelloWorld {
            public static void main(String args[]) {
                ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });
    
                ((ClassPathXmlApplicationContext) context).close();
            }
        }
    

    이제 아래와 같이 myConfiguration.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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
        <bean id="osho" class="com.sample.pojo.Author">
            <property name="firstName" value="Osho" />
            <property name="lastName" value="Jain" />
            <property name="dateOfBirth" value="11 December 1931" />
            <property name="country" value="India" />
        </bean>
    
        <bean id="paulo" class="com.sample.pojo.Author">
            <property name="firstName" value="Paulo" />
            <property name="lastName" value="Coelho" />
            <property name="dateOfBirth" value="24 August 1947" />
            <property name="country" value="India" />
        </bean>
    
        <bean id="validatorBean" class="com.sample.test.BeansValidator">
            <property name="author1">
                <idref bean="Krishna" />
            </property>
    
            <property name="author2">
                <idref bean="paulo" />
            </property>
        </bean>
    
    </beans>
    

    설정 파일을 보았을 때, validatorBean은 id가 'Krishna'인 bean을 검사합니다.

    <bean id="validatorBean" class="com.sample.test.BeansValidator">
            <property name="author1">
                <idref bean="Krishna" />
            </property>
    
            <property name="author2">
                <idref bean="paulo" />
            </property>
        </bean>
    

    id가 'Krishna'인 bean이 존재하지 않으므로, 다음과 같은 오류가 발생합니다.

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'validatorBean' defined in class path resource [myConfiguration.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean name 'Krishna' in bean reference for bean property 'author1'
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
        at com.sample.test.HelloWorld.main(HelloWorld.java:8)
    
  4. ==============================

    4.나는 약간 말문을 열어야한다. 이 예에서는 praveen을 제공합니다. 클래스의 속성이 String 유형이지만 yapkm01의 예에서 속성의 유형이 Point이므로 예외가 발생합니다. idref를 사용할 수 있으려면 String 유형의 또 다른 속성 (여기서는 "message")을 소개해야하며 코드는 다음과 같이 보일 것입니다.

    나는 약간 말문을 열어야한다. 이 예에서는 praveen을 제공합니다. 클래스의 속성이 String 유형이지만 yapkm01의 예에서 속성의 유형이 Point이므로 예외가 발생합니다. idref를 사용할 수 있으려면 String 유형의 또 다른 속성 (여기서는 "message")을 소개해야하며 코드는 다음과 같이 보일 것입니다.

    <property name="message">
        <idref bean="zeroPoint" />
    </property>
    
    <property name="pointA" ref="zeroPoint"/>
    
  5. ==============================

    5.너는 잘못된 행동을하지 않고있다. 코드에서 가 아닌 를 사용해야합니다. 태그는 참조 된 bean의 ID와 동일한 String 유형의 값을 작성하는 데 사용되며 유효성을 확인하기위한 것입니다.

    너는 잘못된 행동을하지 않고있다. 코드에서 가 아닌 를 사용해야합니다. 태그는 참조 된 bean의 ID와 동일한 String 유형의 값을 작성하는 데 사용되며 유효성을 확인하기위한 것입니다.

  6. from https://stackoverflow.com/questions/14607142/spring-idref-usage by cc-by-sa and MIT license