What is best way to read properties from application.properties? - spring

So, I have created configuration class with #Component and #ConfigurationProperties(prefix = "properties"), set default values for some of my application properties and changed some of them in application.yaml/properties
Now, I know I can access it using #Value("properties.*") but it can lead to having many variables which will be repetitive in another classes too
#Value("${properties.user-id-length}")
private int userIdLength;
I also can access my configuration class (as it is Spring Bean) through #Autowire it to variable in every single class I need make use of it. The cons for that is that more complex configuration class containing inner classes, which contain inner classes etc. will not look too great in code
#Autowired // Not recommended, but for simplicity
private MyConfigurationClass myConfigurationClass;
// some method
int userIdLength = myConfigurationClass.getUserIdLength();
String serverLocation = myConfigurationClass.getAmazon().getSes().getSenderEmailAddress()
Another way is to create additional helper class like Constant and set needed static fields with #Value but it can be time consuming and I'm not sure it is THAT different from first solution
public static int USER_ID_LENGTH;
#Value("${properties.user-id-length}")
private void setUserIdLength(int length){
Constant.USER_ID_LENGTH = length;
}
So, which aproach is the best? Or are there another ways to do that?

Well, not much of the feedback but in the meantime I figured out that using both #Value and #ConfigurationProperties leads to some problems.
MyProp.class
#Getter
#Setter
#ConfigurationProperties(prefix = "prop")
public class MyProp{
private String default = "Default String"
}
SomeClass.class
#Component
public class SomeClass.class{
#Value("${prop.default}")
public String message;
}
Above example causes Exception BeanCreationException
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someClass': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'prop.default' in value "${prop.default}"
Explanation to this can be found here in #davidxxx's post and occurs unless we set all fields in application.properties. Because of that my first proposal cannot be done in the terms I thought it can be done and explanation was not easy to find, so I hope it will help someone one day.

Related

Spring Autowire configuration in flink

i am trying to use the comination of flink and springboot and im having some problems.
Lets say i am having this flow.
Getting json string that have one field date that contains date string.
using map function and ObjectMapper to parse it into object of LocalDateTime
print
This is simple usecase that will describe my probem.
So, i have Word Class represnting Word that contains LocalDateTime field.
#Data
public class Word {
#JsonDeserialize(using = LocalDateTimeSerde.class)
LocalDateTime date;
}
The LocalDateTimeDeserlization is looking like that(I want to autowire the app configuration):
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
#JsonComponent
public class LocalDateTimeSerde extends JsonDeserializer<LocalDateTime> {
private final AppConf conf;
#Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(this.conf.getDateFormatter());
return LocalDateTime.parse(jsonParser.getText(), formatter);
}
}
AppConf.java represneting the configuration of the application is:
#Data
#Configuration
#ConfigurationProperties(value = "app")
public class AppConf {
private String dateFormatter;
}
DemoApplication.java:
final StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(1);
String example = "{\"date\":\"2019-01-29 00:00\"}";
var stream = env
.fromElements(example)
.map(x->new ObjectMapper().readValue(x,Word.class))
.returns(Word.class);
stream.print();
env.execute("Demo App");
The exception im getting is :
Caused by: java.lang.IllegalArgumentException: Class com.example.demo.LocalDateTimeSerde has no default (no arg) constructor
The main problem here is that the code of the deserialization is running on the TaskManager and over there springboot doesnt take a part, so it doesn`t inject AppConf into the class.
Adding #NoArgsConstructor will not solve the problem
I think i know why it is hapenning (because flink master serialize the classes to the workers and then springboot doesn`t "ScanComponents" and takes control.
Is there any solution for that? I really want to combine spring with flink also in the worker`s function.
Thanks.
In general, I personally don't think it's a good idea to mix those concepts. The easiest solution is to use AutoWired only on the job manager and use explicit dependency injection when you go into Flink-land.
For example, you could extract the date pattern in the DemoApplication and set it on the ObjectMapper. (Don't forget to initialize ObjectMapper only once in your real code!)
If you really want to use AutoWiring. I guess you need to manually trigger the autowiring on taskmanager. There is a related post specifically for ObjectMapper.

SpEL in #Qualifier refer to same bean

I am interested to inject a bean reference, which is resolved based on another property on the same bean:
#Autowired
#Qualifier("#{'prefix' + actualQualifier}")
private OtherBean otherBean
private String actualQualifier;
This would ensure that the relationship between "actualQualifier" and "otherBean" is correct.
There is a number of beans configured of the type OtherBean.
I can make sure that "actualQualifier" has a value set before autowiring/injection begins.
I am unable to find any way to reference another property value (in the JavaBean sense) on the same bean that is currently being autowired.
AFAIK, this will not work. SpEL has no access to variables of the enclosing class. And anyway, it looks like #Qualifier does not process SpEL expressions.
I did some tests and never found how to use a SpEL expression as a #Qualifier value. This page from Spring forums (and the error messages from Spring) let me think that in fact #Qualifier only takes a String and does not try to evaluate a SpEL expression.
My conclusion is that way will lead you in a dead end.
As suggested in this other answer, I think you'd better use a selector bean and set otherBean in an init method :
#Bean(initMethod="init")
class MyBean {
...
#Autowired
private BeanSelector beanSelector;
private OtherBean otherBean
private String actualQualifier;
public void init() {
otherBean = beanSelector(actualQualifier);
}
...
}
and put all intelligence about the choice of otherBean in beanSelector.

Spring-Wicket: optional but named bean still required

Consider following (wicket) code:
#SpringBean(required=false)
private StatusCheckService service;
In my use case there is no bean of type StatusCheckService in my context.
This is not a problem, it is marked as optional so the (wicket) page will initialize just fine.
However:
#SpringBean(name = "statusCheckService", required=false)
private StatusCheckService service;
This fails:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'statusCheckService' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractBeanFactory.isSingleton(AbstractBeanFactory.java:400)
at org.springframework.context.support.AbstractApplicationContext.isSingleton(AbstractApplicationContext.java:1113)
at org.apache.wicket.spring.SpringBeanLocator.isSingletonBean(SpringBeanLocator.java:100)
at org.apache.wicket.spring.injection.annot.AnnotProxyFieldValueFactory.getFieldValue(AnnotProxyFieldValueFactory.java:140)
I would expect it makes no difference. OK, there is no bean with such a name but I marked it as optional so why the exception? Is there any way around this?
By doing a usage search in eclipse, you can see that the only time the annotation is queried for its required value is on line 215 of AnnotProxyFieldValue:
if (names.isEmpty())
{
if (annot.required())
{
throw new IllegalStateException("bean of type [" + clazz.getName() + "] not found");
}
return null;
}
Here you can see that the 'required' field of the #SpringBean annotation is only used if the names list (set higher in the function) is empty...
This explains the behaviour you are experiencing, because when you don't specify a name, the names list is empty (because it could not find your class), and null is returned. However when you do specify a name it doesn't bother trying to see if the class exists, and so sends your supplied class-name for spring to look up which proceeds to complain when it cannot find the class.
This could be a bug depending on designers intentions, personally I think if you have specified that the field is not required then the function should return early... If you agree then maybe consider putting in a jira ticket with a quick start.
As for a solution, you haven't mentioned much about your use case, and why you need to set the name even though you do not require the bean to be injected. But assuming you are doing it to dynamically inject the bean based on certain criteria, you could do something like the following: (untested)
In your class where the SpringBean is injected, replace:
#SpringBean(name="statusCheckService", required=false)
private StatusCheckService service;
With:
MyCustomSpringBeanInjector injectedService;
And then MyCustomSpringBeanInjector class is something like:
import org.apache.wicket.injection.Injector;
import org.apache.wicket.spring.injection.annot.SpringBean;
public class MyCustomSpringBeanInjector
{
#SpringBean public StatusCheckService service;
public MyCustomSpringBeanInjector()
{
Injector.get().inject(this);
}
}
Then back in the class where the SpringBean was being injected, put something like:
if(statusCheckServiceRequired)
injectedService = new MyCustomSpringBeanInjector();
and replace "service." with "injectedService.service" where necessary.
Obviously this is a qwik-e fix off the top of my head, and I'm sure there's a better way of doing it, but you get the idea! :)
Best of luck!

How do I get a property value from an ApplicationContext object? (not using an annotation)

If I have:
#Autowired private ApplicationContext ctx;
I can get beans and resources by using one of the the getBean methods. However, I can't figure out how to get property values.
Obviously, I can create a new bean which has an #Value property like:
private #Value("${someProp}") String somePropValue;
What method do I call on the ApplicationContext object to get that value without autowiring a bean?
I usually use the #Value, but there is a situation where the SPeL expression needs to be dynamic, so I can't just use an annotation.
In the case where SPeL expression needs to be dynamic, get the property value manually:
somePropValue = ctx.getEnvironment().getProperty("someProp");
If you are stuck on Spring pre 3.1, you can use
somePropValue = ctx.getBeanFactory().resolveEmbeddedValue("${someProp}");
Assuming that the ${someProp} property comes from a PropertyPlaceHolderConfigurer, that makes things difficult. The PropertyPlaceholderConfigurer is a BeanFactoryPostProcessor and as such only available at container startup time. So the properties are not available to a bean at runtime.
A solution would be to create some sort of a value holder bean that you initialize with the property / properties you need.
#Component
public class PropertyHolder{
#Value("${props.foo}") private String foo;
#Value("${props.bar}") private String bar;
// + getter methods
}
Now inject this PropertyHolder wherever you need the properties and access the properties through the getter methods

Spring static initialization of a bean

Hey,
how one should deal with static initializations in Spring ? I mean, my bean has a static initialization
private static final Map<String, String> exceptionMapping = ErrorExceptionMapping.getExceptionMapping();
And I need to take care that ErrorExceptionMapping is loaded before. I tried this:
<bean id="errorExceptionMapping" class="cz.instance.transl.util.ErrorExceptionMapping" />
<bean id="validateService" class="cz.instance.transl.services.ValidateService" depends-on="errorExceptionMapping" >
But I got
java.lang.NoClassDefFoundError: Could not initialize class cz.instance.transl.util.ErrorExceptionMapping
If I omit the static initialization or call the method from within the bean's method, its of course fine. I suppose that Initialization callback (affterPropertiesSet()) wouldn't help here.
Having static dependencies on other beans is not a Spring way.
However, if you want to keep it static, you can initialize it lazily - in that case depends-on can enforce proper initialization order.
EDIT: By lazy loading I mean something like this (I use lazy initialization with holder class idiom here, other lazy initialization idioms can be used instead):
private static class ExceptionMappingHolder {
private static final Map<String, String> exceptionMapping =
ErrorExceptionMapping.getExceptionMapping();
}
and use ExceptionMappingHolder.exceptionMapping instead of exceptionMapping.
You should be able to mark the class with the #Component annotation, then add a non static setter with #Autowired(required=true) annotation for setting the static variable.
Here's a link for more info.

Resources