Using Java Spring Injection with Public Public Final Final Objects (for Jakarta Unstandard)

Disclaimer I understand that trying to use Spring to introduce static variables is considered bad practice (and I know there are ways around it, for example here ). So, ultimately, I plan a redesign, but I'm curious about possible solutions or workarounds.

I use the Jakarta Unstandard tag library (especially useConstants ) to easily output public static final objects to my JSP pages. I want these static objects to be initialized from my database, which means that I need to enter a JDBC template or data source. So I want something like:

 public class MyGroup { // @Autowire or inject somehow? private static /*final?*/ NamedParameterJdbcTemplate jdbcTemplate; public static final MyGroup GROUP_A = new MyGroup("GROUP_A"); public static final MyGroup GROUP_B = new MyGroup("GROUP_B"); public static final MyGroup GROUP_C = new MyGroup("GROUP_C"); // Instance fields private int id; private String name; private String description; /** * Construct a group */ public MyGroup() {} /** * Construct a group using information from the database * @param key the key to match */ public MyGroup(String key) { // Do DB stuff using injected JDBC template this.id = id_from_DB; this.name = name_from_DB; this.description = desc_from_DB; } } 

In my JSP, I could just make ${MyGroup.GROUP_A.id} and somewhere else in the Java code, I could just MyGroup.GROUP_B.getName() .

So the problem is that these groups must be final for the Jakarta library to pick them up, but I cannot statically initialize them through Spring. Thoughts?

+3
source share
1 answer

This is not a problem with spring as much as with a conflict between what you want and what Java allows. You cannot defer the assignment of a static final property. It must be installed when the class is loaded. Therefore, by the time spring can be entered, it is too late.

If you don’t have to be final, you can open some options.

Another possibility is that it may be possible to create an aspect when intercepting access to a property and return the value you want, not the stored value. You can then enter the desired value into the aspect.

I have never done this specifically with static properties, but I assume this is possible. It is not possible to use constant fields (static end fields bound to a constant object or primitive value) like JoinPoint, since java requires them to be inline, but since you are pointing to an object other than String, I think using the aspect can work.

To make sure that spring introduces into your aspect, be sure to let spring know about it through the following:

 <bean id="someId" class="com.yourdomain.YourAspect" factory-method="aspectOf"/> 
+2
source

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


All Articles