Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it advisable to create a request context with ThreadLocal on the Spark framework

Tags:

spark-java

Using the Spark web framework - I'd like to avoid passing all parameters into every method signature (request user, etc). Is it suitable to use a context with static ThreadLocal properties?

I guess we don't have full control which thread services a request but guess Initializing with each call on the Spark API/boundary should be fine.

like image 526
beluga Avatar asked Nov 23 '25 15:11

beluga


1 Answers

I fiddled around a bit and I think I found a good solution for this problem. According to the documentation:

/**
 * Sets an attribute on the request
 * (can be fetched in filters/routes later in the chain)
 *
 * @param attribute The attribute
 * @param value     The attribute value
 */
public void attribute(String attribute, Object value) {
    /* ... */
}

So you can use set an attribute in the request itself and later fetch it. Pretty neat.

like image 87
Luan Nico Avatar answered Nov 25 '25 07:11

Luan Nico