Make sure the spring bean is single point

How can I assure that Spring bean is single?

I would use the ApplicationContext , InitializingBean and BeanNameAware .

In afterPropertiesSet() I would call isSingleton(String) with the name bean.

Is there any other way to make sure the bean is single?

Because according to the API :

Note that it is generally not recommended that an object be dependent on its bean, as this represents a potentially fragile dependency on the external configuration, as well as a possibly unnecessary dependency in the Spring API.

+1
source share
2 answers

If I remember correctly, a bean-installed bean will be single by default (for current versions of spring-library), unless you define a scope of type 'prototype'.

Check: The default scope of spring beans

Quote:

Singleton scope is the default scope in Spring

+5
source

You can do this β€œJava way” with AtomicBoolean :

 private static final created = new AtomicBoolean(); @PostConstruct public void ensureSingleInstance() { if(created.getAndSet(true)) { throw new IllegalStateException("Trying to create second instance"); } } 

But do you really need such a statement? Beans default scope="singleton" ...

+2
source

All Articles