복붙노트

[SPRING] 스프링 자바 설정을 사용하여 싱글 톤 빈으로 프로토 타입 객체 생성하기

SPRING

스프링 자바 설정을 사용하여 싱글 톤 빈으로 프로토 타입 객체 생성하기

여기 내가 지금 잘하고있는 것이 있습니다. 그것이하는 것은 상품 객체의 배열을 반환하는 시장 클래스입니다.

나는 수업 시장이있다.

class market {

    public ArrayList<Items> createItems(HashMap<String,String> map) {
        ArrayList<Items> array = new ArrayList<Items>();
        for (Map.Entry<String, String> m : map.entrySet()) {
            Item item = new Item();
            item.setName(m.key());
            item.setValue(m.value());
            array.add(item);
        }
        return array;
    }
}

class Item은 name과 value에 대한 getter와 setter를 가진 간단한 클래스입니다.

다음은 설정 파일의 모습입니다 :

@Configuration
public class MarketConfig {

    @Bean
    public Market market() {
        return new Market();
    }
}

어떻게 내 코드를 변경하고 싶어 :( 이유 : 나는 원하지 않는다.

Item item = new Item(); 

그때 방법. 봄이 마켓에 주입되기를 원한다)

class market {

    public Item item;
    //getters and setters for item

    public ArrayList<Items> createItems(HashMap<String,String> map) {
        ArrayList<Items> array = new ArrayList<Items>();
        for (Map.Entry<String, String> m : map.entrySet()) {
             item.setName(m.key());
             item.setValue(m.value());
             array.add(item);
        }
        return array;
    }
}

@Configuration
public class MarketConfig {

    @Bean
    @Scope("prototype")
    public Item item() {
        return new Item();
    }

    @Bean
    public Market market() {
        Market bean = new Market();
        bean.setItem(item());
    }
}

나는 item ()을 호출 할 때마다 프로토 타입 범위가 새로운 빈을 제공한다는 것을 안다;  이제 createItems 메소드의 for 루프에서 각 반복마다 새 bean을 원한다. 어떻게 봄을 말해 줄 수 있겠 어.

내가 아는 한 가지 방법은 마입니다.

applicationContext context = new AnnotationConfigApplicationContext();
context.getBean(Item.class);

그러나 내 일을 끝내기위한 다른 방법이 있습니까? 감사

해결법

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

    1.예, 조회 방식을 사용하여 필요에 따라 프로토 타입 메소드를 만들 수 있습니다.

    예, 조회 방식을 사용하여 필요에 따라 프로토 타입 메소드를 만들 수 있습니다.

    public abstract class ItemFactory {
    
        public abstract Item createItem();
    
    }
    

    이제 applicationContext.xml에서 다음을 입력하십시오.

    <bean id="item" class="x.y.z.Item" scope="prototype" lazy-init="true"/>
    

    공장 구성 :

    <bean id="itemFactory" class="x.y.z.ItemFactory">
    <lookup-method name="createItem" bean="item"/>
    </bean>
    

    이제 이것을 사용하기 위해해야 ​​할 일은 모든 bean 내부의 Autowire입니다.

    전화 조회 방법 :

    @Service 
    public class MyService{
    
       @Autowired
       ItemFactory itemFactory;
    
       public someMethod(){
          Item item = itemFactrory.createItem();
       } 
    
    }
    

    createItem ()을 호출 할 때마다 Item 클래스의 새로 생성 된 인스턴스에 대한 참조를 받게됩니다.

    추신 : xml 대신 @Configuration을 사용하고있는 것을 보았습니다. lookup 메서드가 구성 빈 내에 구성 될 수 있는지 확인해야합니다.

    희망이 도움이됩니다.

    업데이트 : 트릭은 간단합니다.

    @Configuration
    public class BeanConfig {
    
        @Bean
        @Scope(value="prototype")
        public Item item(){
            return new Item();
        }
    
    
        @Bean
        public ItemManager itemManager(){
            return new ItemManager() {
    
                @Override
                public Item createItem() {
                    return item();
                }
            };
        }
    }
    
  2. ==============================

    2.Java 8을 사용하는 경우 단순화 할 수 있습니다.

    Java 8을 사용하는 경우 단순화 할 수 있습니다.

    @Configuration
    public class Config {
    
      @Bean
      @Scope(value = "prototype")
      public Item item() {
          return new Item();
      }
    
      @Bean
      public Supplier<Item> itemSupplier() {
          return this::item;
      }
    }
    

    그런 다음 Market 클래스에서이 공급자를 사용하여 프로토 타입 Item Bean을 만들 수 있습니다.

    @Component
    public class Market {
    
      private final Supplier<Item> itemSupplier;
    
      @Autowired
      public Market(Supplier<Item> itemSupplier) {
          this.itemSupplier = itemSupplier;
      }
    
      private Item createItem() {
          return itemSupplier.get();
      }
    
    }
    

    아주 간단하고 추가적인 factory bean이나 인터페이스가 필요 없습니다.

  3. from https://stackoverflow.com/questions/14880847/howto-generate-prototype-objects-with-in-a-singleton-bean-using-spring-java-conf by cc-by-sa and MIT license