How to handle externally stored default values in Domain Class
I want to be able to set default values for some fields in my domain classes. Till now I had a class which stored a Map of settings for my whole project, with a task in mind to move this map into a redis database. The day has come and I moved all开发者_JS百科 the data to redis and created a nice spring bean to get/set the values. However... it seems that default values are set on the domain class instance before bean is injected. This kind of breaks the whole process. Also... there's an issue with unit tests. I've created a class which implements the same interface as the spring bean and holds test values. I wanted to inject it into domain classes, but this fails as well.
So right now I'm trying to find a good way to handle externally stored defauls values for my domain classes with ability to run unit tests. Any thoughts?
There are a few different approaches you could take:
- Introduce a separate bean with the default values so that those are supplied in the same way as they were before. In a separate higher level context or later on in application startup, you could then override the bean definition with the one that pulls from the database
- Use a BeanPostProcessor or BeanFactoryPostProcessor to specify the default values, then use your new bean for retrieving new values
If neither of these answers is helpful, please post your setup and example code so I can get a clearer picture of what you're trying to do.
What I did in the end: I've created a class which is connecting to Redis and gets me all the data I require. For unit testing I've created a copy of this class, it implements the same interface but instead of getting the data from Redis it has a simple Map inside and get's the data from there. In the end it acts the same, but the data is stored internally. So in my unit tests I just inject this Unit test version of this class where appropriate.
Probably not the best solution there is but it worked for me for the last few months.
精彩评论