Spring mvc 如何将EJB与Springbeans集成并处理Singleton

Spring mvc 如何将EJB与Springbeans集成并处理Singleton,spring-mvc,jakarta-ee,dependency-injection,singleton,Spring Mvc,Jakarta Ee,Dependency Injection,Singleton,我有一个在clear Java EE中使用依赖项注入和单例的工作项目: @javax.inject.Singleton public class SomeSingleton {...} 我在应用程序中的任何位置使用它,并收到相同的实例: @Inject SomeSingleton instanceOfSingleton; 最近我不得不添加Spring模块,它使用我的SomeSingleton类。Spring需要@Bean注释手动生成实例: @Bean public SomeSingleton

我有一个在clear Java EE中使用依赖项注入和单例的工作项目:

@javax.inject.Singleton
public class SomeSingleton {...}
我在应用程序中的任何位置使用它,并收到相同的实例:

@Inject SomeSingleton instanceOfSingleton;
最近我不得不添加Spring模块,它使用我的SomeSingleton类。Spring需要@Bean注释手动生成实例:

@Bean
public SomeSingleton someSingleton(){
    return new SomeSingleton();
}

问题是我现在有两个singleton实例。如何解决这个问题?

一方面,让一个单例从任何地方访问Spring的ApplicationContext,如下所述:

然后使用以下代码段:

@javax.inject.Singleton
public class SomeSingleton {
    @PostConstruct
    void post() {
        ApplicationContext ctx = SpringApplicationContext.get();
        AutowireCapableBeanFactory awcbf = ctx.getAutowireCapableBeanFactory();
        awcbf.configureBean(this, "someSingleton");
    }
}

好的,我找到了一个解决方案,但我认为它并不优雅,因为我必须替换所有@Inject注释。这是:

在Spring配置文件中(基于注释):

我的类名为SpringApplicationContext(无需实现ApplicationContextAware):


我不知道我的解决方案是否还有其他缺点:(

哪个版本的Spring?也许你是对的,但是如何将“this”存储到Spring的ApplicationContext中?删除@Bean注释后,我收到错误:org.springframework.beans.factory.NoSuchBean定义异常:没有符合条件的[example.MyClassName]类型的Bean)为依赖项找到:应至少有1个bean符合此依赖项的autowire候选。依赖项批注:{@org.springframework.beans.factory.annotation.Autowired(required=true)}我没有Spring xml配置,我有一个基于注释的配置。所以我必须像这样接收ApplicationContainer:ApplicationContext context=new AnnotationConfigApplicationContext(SecurityConfig.class);在这之后,我会收到无限多的错误(如有循环)。若我删除@Bean注释,我仍然会收到我之前评论中提到的错误。我认为这是因为Springs配置在JavaEE依赖注入之前工作。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private void configureApplicationContext(ApplicationContext context) {
        SpringApplicationContext.setApplicationContext(context);
    }

    @Bean
    public SomeSingleton someSingleton() {
        return new SomeSingleton();
    }

    //the rest of class code

}
public class SpringApplicationContext {

  private static ApplicationContext CONTEXT;

  public static void setApplicationContext(ApplicationContext context){
    CONTEXT = context;
  }

  public static Object getBean(String beanName) {
    return CONTEXT.getBean(beanName);
  }

  public static <T> T getBean(Class<T> type) {
      return CONTEXT.getBean(type);
  }

  public static ApplicationContext get() {
      if (CONTEXT == null) {
          throw new RuntimeException();
      }
      return CONTEXT;
  }
}
private SomeSingleton someSingleton = SpringApplicationContext.getBean(SomeSingleton.class);