How to enforce Spring beans scope prototype

I have a Spring bean state. How can I apply my scope to a prototype in my application?

How can I prevent another developer of my project from implementing this bean using a singleton scope?

I know that you can adjust the scope through annotation or through the xml configuration. From what I saw when using Spring 3, the area configured by the annotation is overridden by the area defined manually in xml. How can I apply my scope, either through configuration or programmatically, so that my bean will never be used as a singleton?

I was thinking about inspecting the bean area when starting the application, but this does not seem like an elegant solution.

+2
source share
3 answers

It's not elegant, but AFAIK is the only way to achieve what you are looking for.

public class MyStatefulBean implements InitializingBean, ApplicationContextAware, BeanNameAware { private String myName; private ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } @Override public void setBeanName(String s) { this.myName = s; } @Override public void afterPropertiesSet() throws Exception { if(this.context.isSingleton(this.myName)) throw new RuntimeException("Bean CANNOT be singleton"); } } 
+3
source

Document? There is no way to find out if anyone supports the bean reference and reuses it or shares it by streams when they had to use getBean() to get the prototype.

Spring cannot stop peers from writing code that is simply wrong, and that’s all there is to use.

0
source

If you do not want to rely on the fact that the API user does what is expected of them, output a bean through the factory.

0
source

Source: https://habr.com/ru/post/950062/


All Articles