简体   繁体   中英

Assure Spring bean is singleton

How can I assure that a Spring bean is a singleton?

I'd implement the Interfaces ApplicationContext , InitializingBean and BeanNameAware .

In afterPropertiesSet() I'd call isSingleton(String) with the Bean's name.

Is there another way to make sure that a Bean is a singleton?

Because according to the API :

Note that it is not usually recommended that an object depend on its bean name, as this represents a potentially brittle dependence on external configuration, as well as a possibly unnecessary dependence on a Spring API.

If i recall correctly, a spring-managed bean will be a singleton by default (for current versions of the spring-library), unless you define the scope to be of type 'prototype'.

Check: Default scope of spring beans

Quote:

The singleton scope is the default scope in Spring

You can do it " the Java way " with AtomicBoolean flag:

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 an assertion? Beans have scope="singleton" by default...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM