Finding singleton beans state

Today we found this template in our code:

class Foo { private List<String> errors; public void addError(String error) { ... } public List<String> getErrors(); } 

While the code is running, this is a singleton Spring bean, and it is introduced in several independent places, and bean consumers assume that each of them has its own list of errors. Thus, it introduces subtle errors.

The obvious solution is to train developers to avoid such an error, but I was wondering if there is a static or temporary code analysis tool that can find such an error.

For example, the bean post processor could parse the bean before returning it and look for private fields that are not @Autowired .

+6
source share
2 answers

After we filled some more brains (ours and other peoples), we came up with this approach:

  • Set up a BeanPostProcessor , which ensures that all singleton beans (that is, where the scope of the Singleton bean is) have a custom @Stateless for the actual bean type.

    We chose custom annotation instead of reusing @Singleton , as we need this functionality elsewhere.

    If the annotation is missing, factory throws an error.

  • In unit test, we use ClassPathScanningCandidateComponentProvider without custom annotation to find all classes in the classpath. Then we can run complex and expensive tests to make sure that the bean does not have a state that changes after the initial configuration (that is, after auto-tuning has occurred).

The second step can be simplified a bit if we move the auto-substitution field to the constructor, but we don’t like methods that take many arguments. It would be nice if the Java or IDE could generate compilers from the bean code. Since this is not the case, we adhere to autowave fields and / or setters.

+1
source

You can create a JUnit test that loads the configuration of your application. This can combine a ListableBeanFactory from here:

Can I dynamically create a list by scanning beans in the spring configuration file?

using "isSingleton" here:

How to scale prototype spring beans

i.e. list all the beans in the application context, and then check what singletones are.

This will allow you to find all the singleton beans ... although in reality it will not interfere with your case with an error when someone refers to one of these singlets, as if it were not.

0
source

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


All Articles