Java Spring应用程序中特定原型bean的已创建实体数?
有没有办法获取Spring应用程序中已经创建的特定原型bean实体的编号和一些标识信息Java Spring应用程序中特定原型bean的已创建实体数?,java,spring,prototype,javabeans,Java,Spring,Prototype,Javabeans,有没有办法获取Spring应用程序中已经创建的特定原型bean实体的编号和一些标识信息 添加。在我们的项目中,我们有400多个原型bean,我想跟踪执行期间创建的bean的状态以及每种类型的实体的数量。您可以通过发布和侦听应用程序事件来完成 创建您自己的事件 创建原型bean时,从中发送事件 创建计数应用程序侦听器,并侦听收入创建事件 下面是一个例子 Spring不管理原型bean的整个生命周期:容器实例化、配置、装饰和以其他方式组装原型对象,将其交给客户机,然后不再了解该原型实例。 简单变体
添加。在我们的项目中,我们有400多个原型bean,我想跟踪执行期间创建的bean的状态以及每种类型的实体的数量。您可以通过发布和侦听应用程序事件来完成
public class PrototypeCreationEvent extends ApplicationEvent {
private String beanName;
public PrototypeCreationEvent(Object source , String beanName) {
super(source);
this.beanName = beanName;
}
public String getBeanName(){
return beanName;
}
}
public class PrototypeCreationListener implements ApplicationListener<PrototypeCreationEvent> {
private ConcurrentMap<String,AtomicInteger> prototypeCreationStatistic = new ConcurrentHashMap<>();
//or from guava AtomicLongMap prototypeCreationStatistic = AtomicLongMap.create();
@Override
public void onApplicationEvent(PrototypeCreationEvent event) {
prototypeCreationStatistic.computeIfAbsent(event.getBeanName() , k->new AtomicInteger(0)).incrementAndGet();
System.out.println(event);
}
public ConcurrentMap<String,AtomicInteger> getPrototypeCreationStatistic(){
return prototypeCreationStatistic;
}
}
public abstract class PrototypeCreationPublisher implements BeanNameAware , ApplicationEventPublisherAware ,InitializingBean {
private String beanName;
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setBeanName(String name) {
this.beanName = name;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println();
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@PostConstruct //or use interface InitializingBean
public void sendEventAfterCreation() throws Exception {
applicationEventPublisher.publishEvent(new PrototypeCreationEvent(this , beanName));
}
}
@Component(value = BeanDefinition.SCOPE_PROTOTYPE)
public class PrototypeA extends PrototypeCreationPublisher{
}
@Component(value = BeanDefinition.SCOPE_PROTOTYPE)
public class PrototypeB extends PrototypeCreationPublisher{
}
结果:
PrototypeB count = 1
PrototypeA count = 3
我找到了一种方法查看创建的原型bean的实际图片。 我使用免费的VisualVM内存分析器 在Sampler选项卡中,您可以看到创建的类的所有实例,包括单例bean和原型bean 您将看到自己的包和类的名称。在这种情况下:
- prototype是一个包含我的原型bean的包
- singleton是一个包含我的singleton bean的包
- newclasses是一个包含由new操作符创建的类的包
谢谢。有没有办法从ApplicationContext获取信息?好的。我会试试你的方法。也许我不明白。。。但是我可以通过在控制台中从bean的构造函数打印信息来获得关于创建bean的信息。请看我更正的问题。在我们的项目中,我们有超过400个原型bean,所以我想检查创建了哪些原型bean以及它们的数量。。。进入听者。听者是辛格尔顿。当事件进入侦听器时,保存它。如果您使用许多不同的Bean原型,请使用您自己的事件和一些信息,如BEN的类型。您需要知道一个原型类的计数还是多个原型类的计数?
PrototypeB count = 1
PrototypeA count = 3