복붙노트

[SPRING] Spring에서는 autowired bean 내부에서 새로운 bean을 autowire 할 수 있습니까?

SPRING

Spring에서는 autowired bean 내부에서 새로운 bean을 autowire 할 수 있습니까?

나는 보통 봄 물건에 @Autowire 것들을 그냥. 그러나 autowired 될 수있는 값을 필요로하는 객체를 동적으로 생성해야하는 상황이 발생했습니다.

어떻게해야합니까? 내가 할 수있는 것은 autowired 값을 새로운 객체의 생성자에 수동으로 전달하는 것입니다. 내가하고 싶은 것은 새로운 오브젝트를 만들 때 자동으로 추가하는 것입니다.

@Service
public class Foo {
    @Autowired private Bar bar;

    /** This creates Blah objects and passes in the autowired value. */
    public void manuallyPassValues() {
        List<Blah> blahs = new LinkedList<Blah>();
        for(int i=0; i<5; ++i) {
            Blah blah = new Blah(bar);
            blahs.add(blah);
        }
        // ...
    }

    /** This creates Blah objects and autowires them. */
    public void useAutowire() {
        List<Blah> blahs = new LinkedList<Blah>();
        for(int i=0; i<5; ++i) {
            // How do I implement the createAutowiredObject method?
            Blah blah = createAutowiredObject(Blah.class);
            blahs.add(blah);
        }
        // ...
    }
}

이상적으로는이 빈에 어떤 설정 정보도 없다. 그것은 autowired이기 때문에, 새로운 bean의 autowiring을 필요로하는 어떤 객체도 autowiring을 통해 사용할 수 있어야합니다.

해결법

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

    1.AutowireCapableBeanFactory를 사용할 수 있습니다 :

    AutowireCapableBeanFactory를 사용할 수 있습니다 :

    @Service 
    public class Foo { 
        @Autowired private AutowireCapableBeanFactory factory; 
    
        private <T> T createAutowiredObject(Class<T> c) {
            return factory.createBean(c);
        }
        ...
    }
    
  2. from https://stackoverflow.com/questions/2383205/in-spring-can-i-autowire-new-beans-from-inside-an-autowired-bean by cc-by-sa and MIT license