Java 我可以在一个用@PostConstruct注释的方法中获取所有bean吗?

Java 我可以在一个用@PostConstruct注释的方法中获取所有bean吗?,java,spring,Java,Spring,据我所知,用@PostConstruct注释的方法将在其bean初始化后执行 我能用这个方法得到所有的豆子吗? 像这样 @CustomAnnotation public class Foo { } @Service public class TestBean { @Autowired private Application context; @PostContruct public void init() { // get all beans annota

据我所知,用@PostConstruct注释的方法将在其bean初始化后执行

我能用这个方法得到所有的豆子吗? 像这样

@CustomAnnotation
public class Foo {
}

@Service
public class TestBean {
   @Autowired
   private Application context;

   @PostContruct
   public void init() {
      // get all beans annotated with @CustomAnnotation
      context.getBeansWithAnnotation(CustomAnnotation.class);
      // to do something...
   }
}


如果TestBean是在Foo之前初始化的,那么在init()中是否可以检测到Foo?

对于单例bean,Spring初始化至少有两个不同的步骤

在创建实际的单例bean实例并调用
@PostConstruct
方法之前,bean工厂读取所有可用的配置(例如XML文件、Groovy脚本、
@Configuration
类、其他)并注册所有遇到的bean定义

getBeansWithAnnotation()
应该找到一个
Foo
bean,如果它不是从它的bean定义创建的,那么当您在
@PostConstrust
中请求它时,它将被创建。您可以尝试使用强制执行此方案,但这可能会导致循环依赖性问题:

@Component
@DependsOn("testBean")
@CustomAnnotation
public class Foo {
}

@Service("testBean")
public class TestBean {

   @Autoware
   private Application context;

   @PostContruct
   public void init() {
      context.getBeansWithAnnotation(CustomAnnotation.class);
   }
}

谢谢您的回答,这意味着FooBean将在init()中初始化吗?如果它以前没有初始化的话,那么它可能会被初始化。不过,如果
Foo
@Lazy
或者用
@Transactional
之类的注释,你也可能会得到一个代理对象。好吧,非常感谢,你让我了解了更多关于春季bean生命周期的信息。我在谷歌上搜索了autowared,但找不到任何资源@Karol DowbeckiDid你是说
@Autowired
而不是
@Autoware
?@加载。。。谢谢你提醒我