programing

ApplicationContext 자체를 주입하는 방법

bestprogram 2023. 8. 5. 10:47

ApplicationContext 자체를 주입하는 방법

주사를 놓고 싶습니다.ApplicationContext그 자체가 콩이.

비슷한 것

public void setApplicationContext(ApplicationContect context) {
  this.context = context;
}

봄에 그것이 가능합니까?

이전 의견은 괜찮지만, 저는 보통 다음을 선호합니다.

@Autowired private ApplicationContext applicationContext;

간편, 사용하기ApplicationContextAware인터페이스

public class A implements ApplicationContextAware {
  private ApplicationContext context;

  public void setApplicationContext(ApplicationContext context) {
      this.context = context;
  }
}

그런 다음 실제 응용프로그램 컨텍스트에서 콩을 참조하면 됩니다.

<bean id="a" class="com.company.A" />

예, ApplicationContextAware 인터페이스만 구현합니다.

위에서 @Autowire가 아직 작동하지 않음에 대한 몇 가지 의견을 보았습니다.다음은 도움이 될 수 있습니다.

이것은 작동하지 않습니다.

@Route(value = "content", layout = MainView.class)
public class MyLayout extends VerticalLayout implements RouterLayout {

  @Autowired private ApplicationContext context;

   public MyLayout() {
    comps.add(context.getBean(MyComponentA.class)); // context always null :(
}

이 작업을 수행해야 합니다.

 @Autowired
  public MyLayout(ApplicationContext context) {
    comps.add(context.getBean(MyComponentA.class)); //context is set :)
}

또는 다음과 같습니다.


@PostConstruct
    private void init() {
    comps.add(context.getBean(MyComponentA.class)); // context is set :)
}

또한 업로드는 @PostConstruct의 범위 내에서 설정해야 하는 또 다른 구성 요소입니다.이건 제가 이해하기엔 악몽이었어요.이것이 도움이 되길 바랍니다!

아래와 같이 @Scope 주석이 당신의 Bean에 필요할 수 있다는 것을 거의 잊어버렸습니다.빈이 생성되기 전에 UI가 인스턴스화/연결되지 않아 Null 참조 예외가 발생하므로 빈 내 업로드를 사용하는 경우가 이에 해당합니다.@Route를 사용할 때는 그렇게 하지 않지만 @Component를 사용할 때는 그렇게 할 것입니다. 따라서 후자는 옵션이 아니며 @Route를 사용할 수 없는 경우에는 @Configuration 클래스를 사용하여 프로토타입 범위로 빈을 만드는 것이 좋습니다.

@Configuration
public class MyConfig {
  @Bean
  @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
  public MyComponentA getMyBean() {
    return new MyComponentA();
  }
}

특별한 해결책: 모든 (스프링이 아닌) 클래스에서 봄콩을 얻습니다.

@Component
public class SpringContext {
    private static ApplicationContext applicationContext;

    @Autowired
    private void setApplicationContext(ApplicationContext ctx) {
        applicationContext = ctx;
    }

    public static <T> T getBean(Class<T> componentClass) {
        return applicationContext.getBean(componentClass);
    }
}

언급URL : https://stackoverflow.com/questions/4914012/how-to-inject-applicationcontext-itself