IT이야기

봄에 리스트빈을 어떻게 정의하나요?

cyworld 2022. 6. 8. 23:41
반응형

봄에 리스트빈을 어떻게 정의하나요?

어플리케이션의 단계를 정의하기 위해 스프링을 사용하고 있습니다.필요한 클래스(여기에서는Configurator)가 스테이지와 함께 주입됩니다.
이제 다른 클래스의 스테이지 목록이 필요합니다.LoginBean.그Configurator스테이지 리스트에 접속할 수 없습니다

반을 바꿀 수 없다Configurator.

내 아이디어:
Stages라고 하는 새로운 콩을 정의하여 주입합니다.Configurator그리고.LoginBean이 아이디어의 문제점은 이 속성을 변환하는 방법을 모른다는 것입니다.

<property ...>
  <list>
    <bean ... >...</bean>
    <bean ... >...</bean>
    <bean ... >...</bean>
  </list>
</property>

콩으로 만들다

다음과 같은 것은 동작하지 않습니다.

<bean id="stages" class="java.util.ArrayList">

누가 나 좀 도와줄래?

spring util 네임스페이스를 Import합니다.다음으로 리스트 빈을 다음과 같이 정의할 수 있습니다.

<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/util
                    http://www.springframework.org/schema/util/spring-util-2.5.xsd">


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

value-type은 사용하는 제네릭타입으로 옵션입니다.속성을 사용하여 목록 구현 클래스를 지정할 수도 있습니다.list-class.

다음은 한 가지 방법입니다.

<bean id="stage1" class="Stageclass"/>
<bean id="stage2" class="Stageclass"/>

<bean id="stages" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="stage1" />
            <ref bean="stage2" />                
        </list>
    </constructor-arg>
</bean>

다른 옵션은 JavaConfig를 사용하는 것입니다.모든 스테이지가 이미 스프링빈으로 등록되어 있다고 가정하면 다음과 같이 해야 합니다.

@Autowired
private List<Stage> stages;

스프링이 자동으로 이 목록에 삽입됩니다.순서를 유지할 필요가 있는 경우(상위 솔루션에서는 그렇게 하지 않습니다)에는, 다음의 방법으로 실행할 수 있습니다.

@Configuration
public class MyConfiguration {
  @Autowired
  private Stage1 stage1;

  @Autowired
  private Stage2 stage2;

  @Bean
  public List<Stage> stages() {
    return Lists.newArrayList(stage1, stage2);
  }
}

질서를 유지하기 위한 다른 솔루션은@Order콩 주석그러면 주석 값 오름차순으로 정렬된 콩이 목록에 포함됩니다.

@Bean
@Order(1)
public Stage stage1() {
    return new Stage1();
}

@Bean
@Order(2)
public Stage stage2() {
    return new Stage2();
}
<bean id="someBean"
      class="com.somePackage.SomeClass">
    <property name="myList">
        <list value-type="com.somePackage.TypeForList">
            <ref bean="someBeanInTheList"/>
            <ref bean="someOtherBeanInTheList"/>
            <ref bean="someThirdBeanInTheList"/>
        </list>
    </property>
</bean>

그리고 SomeClass에서는:

class SomeClass {

    List<TypeForList> myList;

    @Required
    public void setMyList(List<TypeForList> myList) {
        this.myList = myList;
    }

}

Stacker는 훌륭한 답변을 제시했습니다.저는 한 걸음 더 나아가서 Spring 3 EL Expression을 사용하고 싶습니다.

<bean id="listBean" class="java.util.ArrayList">
        <constructor-arg>
            <value>#{springDAOBean.getGenericListFoo()}</value>
        </constructor-arg>
</bean>

util:list에서 이 작업을 수행할 방법을 찾고 있었는데 변환 오류로 인해 제대로 작동하지 않았습니다.

찾으시는 것 같습니다.

ListFactoryBean 인스턴스를 선언하고 목록을 속성으로 인스턴스화합니다.<list>원소를 그것의 가치로, 그리고 콩을 줍니다.id기여하다.그런 다음 선언된 명령어를 사용할 때마다id로서ref또는 다른 bean 선언과 마찬가지로 목록의 새 복사본이 인스턴스화됩니다.또, 다음과 같이 지정할 수도 있습니다.List사용할 클래스입니다.

 <bean id="student1" class="com.spring.assin2.Student">  
<property name="name" value="ram"></property>  
<property name="id" value="1"></property> 
<property name="listTest">
        <list value-type="java.util.List">
            <ref bean="test1"/>
            <ref bean="test2"/>
        </list>
    </property>
</bean>  

나중에 이러한 콩(test1, test2)을 정의합니다.

util 네임스페이스를 사용하면 응용 프로그램 컨텍스트에서 목록을 빈으로 등록할 수 있습니다.그런 다음 목록을 다시 사용하여 다른 콩 정의에 주입할 수 있습니다.

Jakub의 답변 외에 JavaConfig를 사용할 계획이라면 다음과 같이 자동 접속할 수도 있습니다.

import com.google.common.collect.Lists;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

<...>

@Configuration
public class MyConfiguration {

    @Bean
    public List<Stage> stages(final Stage1 stage1, final Stage2 stage2) {
        return Lists.newArrayList(stage1, stage2);
    }
}

지우는 예요.id<list>아아아아아아아아아아아아아아아아아아악

<property name="listStaff">
  <list>
    <bean class="com.test.entity.Staff">
        <constructor-arg name="name" value = "Jonh"/>
        <constructor-arg name="age" value = "30"/>
    </bean>
    <bean class="com.test.entity.Staff">
        <constructor-arg name="name" value = "Jam"/>
        <constructor-arg name="age" value = "21"/>
    </bean>
  </list>
</property>

문자열 목록을 주입합니다.

다음과 같은 문자열 목록을 포함하는 국가 모델 클래스가 있다고 가정합니다.

public class Countries {
    private List<String> countries;

    public List<String> getCountries() {
        return countries;
    }   

    public void setCountries(List<String> countries) {
        this.countries = countries;
    }

}

다음 xml 정의에서는 국가별 빈 목록과 주입 목록을 정의합니다.

<bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
   <property name="countries">
      <list>
         <value>Iceland</value>
         <value>India</value>
         <value>Sri Lanka</value>
         <value>Russia</value>
      </list>
   </property>
</bean>

참조 링크

Pojos 주입 목록

다음과 같은 모델 클래스가 있다고 가정합니다.

public class Country {
    private String name;
    private String capital;
    .....
    .....
 }

public class Countries {
    private List<Country> favoriteCountries;

    public List<Country> getFavoriteCountries() {
        return favoriteCountries;
    }

    public void setFavoriteCountries(List<Country> favoriteCountries) {
        this.favoriteCountries = favoriteCountries;
    }

}

Bean Definitions(빈 정의)

 <bean id="india" class="com.sample.pojo.Country">
  <property name="name" value="India" />
  <property name="capital" value="New Delhi" />
 </bean>

 <bean id="russia" class="com.sample.pojo.Country">
  <property name="name" value="Russia" />
  <property name="capital" value="Moscow" />
 </bean>


 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="favoriteCountries">
   <list>
    <ref bean="india" />
    <ref bean="russia" />
   </list>
  </property>
 </bean>

참조 링크

util:list에서 list-class 속성을 사용하여 특정 유형의 스탠드아론 목록을 만듭니다.예를 들어 ArrayList 유형의 목록을 작성하는 경우:

<util:list id="namesList" list-class="java.util.ArrayList" value-type="java.lang.String">
  <value>Abhay</value>
  <value>ankit</value>
  <value>Akshansh</value>
  <value>Db</value>
</util:list>

또는 LinkedList 유형의 목록을 작성할 경우 다음과 같이 하십시오.

<util:list id="namesList" list-class="java.util.LinkedList" value-type="java.lang.String">
  <value>Abhay</value>
  <value>ankit</value>
  <value>Akshansh</value>
  <value>Db</value>
</util:list>

그리고 봄철에 일부 부동산에서 세트를 주입하는 방법은 다음과 같습니다.

<bean id="process"
      class="biz.bsoft.processing">
    <property name="stages">
        <set value-type="biz.bsoft.AbstractStage">
            <ref bean="stageReady"/>
            <ref bean="stageSteady"/>
            <ref bean="stageGo"/>
        </set>
    </property>
</bean>

언급URL : https://stackoverflow.com/questions/2416056/how-to-define-a-list-bean-in-spring

반응형