简体   繁体   中英

Preventing a setter being called twice in a Spring bean?

I am being asked by a colleague to move our setters to constructors, in our Spring beans, since "the setter exposes a private variable that could be potentially changed after the construction phase in Spring".

While I can appreciate the sentiment, I am not sure this is the best approach? For this reason I am wondering whether there are ways in a Spring bean to prevent a setter from being called twice or whether we should have a check to see if we are before the post-construct phase?

My worry is the constructor uses indexes, rather than named properties. From a code maintenance point of view this is not very friendly.

Spring supports field value insertion through reflection when you use @Autowired or @Inject on a private field. This way you do not have expose a setter nor use a constructor for dependency injection.

If you want the setter to be present you might consider defining your own annotation, defining a pointcut and creating an aspect that prevents method execution if the method has been called on the object at least once.

Personally I prefer having these fields populated through the constructor and marked as final. The amount of boiler-plate generated by this may sometimes be prohibitive when thinking about the readability of the code. To increase readability you may want to use @Qualifier or @Named annotations to further specify which object should satisfy the dependency when there are multiple possibilities.

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