To provide nicer logging when a Spring property is invalid - java

Using a application.properties file my Spring Boot app can use some property values in it. A way to make sure a mandatory value must present is to add an annotation #Value for the property. The problem with this is the app fails miserably if the property value is not there in the properties file.
I am after a nicer less horrible way to say printing out a log line about "Property A is missing" instead of a whole stack trace. Is there a way to do this while still using #Value to initialise the properties? For example, property A is mandatory, an error is logged before app exits; property B is missing but not mandatory, a warning is logged and app continues.

If you can identify all property, then you can write a method in Application class with #Postconstruct, and inside your method, you can manually validate and log them
#Autowired
private Environment environment;
#PostConstruct
private void validateProperties() {
environment.getProperty(key);
.....
......
}
Alternatively, you can write your custom EnvironmentPostProcessor, and iterate all properties and log whichever is null/empty.

As you're using spring-boot consider creating a #ConfigurationProperties class rather than using the #Value annotation.
By doing that you can do your validations using Bean Validation, also in the same class, you can implement the interface InitializingBean and add extra validations/log messages as you with.
Follow this link on Spring's official docs to read more about #ConfigurationProperties.

Related

How to observe the Application Context at runtime (while debugging)

I am debugging my Java Spring service and I get an #Autowired variable as null, when it shouldn't be.
Since I have declared the service's class as #Service, I want to double-check that my bean was scanned by Spring and included in the Application Context.
Therefore, I want to be able to observe in Eclipse the contents of the Application Context.
How is this possible?
inject ApplicationContext into a bean that you can debug and call #getBeanDefinitionNames
I am not sure if this is the best way but without adding any extra framework,if you just want to check if dependencies are injected correctly or not ,you can firstly remove #Autowired annotation from the fields.
Now create a parameterized constructor and annotate the constructor with #Autowired. Spring will try to inject all the beans through the constructor.
http://www.tutorialspoint.com/spring/spring_autowired_annotation.htm
Now you can put breakpoint inside the constructor to check what value is getting injected.
Hope this helps.
There is a workaround to get the WebApplicationContext in the debugger without changing the source code.
The RequestContextUtils#findWebApplicationContext method will help us with this.
You need to pass the current request to it, which can also be obtained using the static method:
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
By combining these calls, you can get the context anywhere in the web application in the debugger and call any of its methods:
RequestContextUtils
.findWebApplicationContext(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest())
.getBeanDefinitionNames();
Slightly prettier version:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
WebApplicationContext webApplicationContext = RequestContextUtils.findWebApplicationContext(request);
webApplicationContext.getBeanDefinitionNames();
you can use log4j.jar to output all the WARNINGS, DEBUGS, INFO once you start your server. Follow the below link http://www.tutorialspoint.com/spring/logging_with_log4j.htm. I have a working example at my other laptop, can post the code. Let me know if you need it

Spring 4 conditional - Accessing a resource

Doing my first steps with spring 4 I tried the #Conditional annotation following this article.
My problem -
I would like to get access to a classpath resource (basically a properties file) from method matches in class OnSystemPropertyCondition.
To do that currently I'm loading the required properties file from the matches method every time it is invoked (which means for every class annotated with the ConditionalOnSystemProperty annotation).
This is a bit ugly. I thought that an elegant solution would be to simply autowire my resource or some properties (using the #Value annotation) but this can't be done since this class gets instanciated before the beans.
Any suggestions than can help me avoid reload this resource again and again?
The single method of the annotation gets in its signature the input param ConditionContext context. You can obtain an Environment from the context by calling context.getEnvironment(). The environment gives access to all my resources (look at this to see how to get access to your resources via spring environment).

Is Spring's #Value annotation part of internationalization?

I am working on a project where internationalized messages are retrieved using the #Value annotation.
e.g.:
#Value("${email.newUser.subject}")
private String NEW_USER_SUBJECT;
#Value("${email.newUser.message}")
private String NEW_USER_MESSAGE;
However, as part of my investigation, it appears that the #Value annotation is used to get a property from a property file and does not link into to automatic lookup of the correct version of the message.properties. Therefore as I understand it, this is only working by coincidence because we have currently only a single message.properties file.
Can anyone in the know tell me if I have the correct understanding of the situation?
The Answer is No, the #Value annotation is not part of Internationalization. It's use in conjunction with Internationalization is an error and will break when you try to change the Local.

Spring #Value annotation always evaluating as null?

So, I have a simple properties file with the following entries:
my.value=123
another.value=hello world
This properties file is being loaded using a PropertyPlaceHolderConfigurer, which references the properties file above.
I have the following class, for which I'm trying to load these properties in to like so:
public class Config
{
#Value("${my.value}")
private String mValue;
#Value("${another.value}")
private String mAnotherValue;
// More below...
}
The problem is that, mValue and mAnotherValue are ALWAYS null... yet in my Controllers, the value is being loaded just fine. What gives?
If instances of Config are being instantiated manually via new, then Spring isn't getting involved, and so the annotations will be ignored.
If you can't change your code to make Spring instantiate the bean (maybe using a prototype-scoped bean), then the other option is to use Spring's load-time classloader weaving functionality (see docs). This is some low-level AOP which allows you to instantiate objects as you normally would, but Spring will pass them through the application context to get them wired up, configured, initialized, etc.
It doesn't work on all platforms, though, so read the above documentation link to see if it'll work for you.
I had similar issues but was a newbie to Spring.
I was trying to load properties into an #Service, and tried to use #Value to retrieve the property value with...
#Autowired
public #Value("#{myProperties['myValue']}") String myValue;
I spend a whole day trying various combinations of annotations, but it always returned null.
In the end the answer as always is obvious after the fact.
1) make sure Spring is scanning your class for annotations by including the package hierachy
In your servlet.xml (it will scan everything below the base value you insert.
2) Make sure you are NOT 'new'ing the class that you just told Spring to look at. Instead, you use #Autowire in the #Controller class.
Everything in Spring is a Singleton, and what was happening was Spring loaded the values into its Singleton, then I had 'new'ed another instance of the class which did not contain the newly loaded values so it was always null.
Instead in the #Controller use...
#Autowired
private MyService service;
Debugging...
One thing I did to find this was to extend my Service as follows...
#Service
public class MyService implements InitializingBean
Then put in debug statements in...
#Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
LOGGER.debug("property myValue:" + myValue);
}
Here I could see the value being set on initialization, and later when I printed it in a method it was null, so this was a good clue for me that it was not the same instance.
Another clue to this error was that Tomcat complained of Timeouts trying to read from the Socket with Unable to parse HTTPheader... This was because Spring had created an instance of the service and so had I, so my one was doing the real work, and Spring was timing out on its instance.
See my answer here.
I ran into the same symptoms (#Value-annotated fields being null) but with a different underlying issue:
import com.google.api.client.util.Value;
Ensure that you are importing the correct #Value annotation class! Especially with the convenience of IDEs nowadays, this is a VERY easy mistake to make (I am using IntelliJ, and if you auto-import too quickly without reading WHAT you are auto-importing, you might waste a few hours like I did).
The correct import is:
org.springframework.beans.factory.annotation.Value
As its working with #Controller, it seems you are instantiating Config yourself. Let the Spring instantiate it.
You can also make your properties private, make sure your class is a Spring bean using #Service or #Component annotations so it always gets instantiated and finally add setter methods annotated with #Value . This ensures your properties will be assigned the values specified in your application.properties or yml config files.
#Service
public class Config {
private static String myProperty;
private static String myOtherProperty;
#Value("${my.value}")
public void setMyProperty(String myValue) {
this.myProperty = myValue;}
#Value("${other.value}")
public void setMyOtherProperty(String otherValue) {
this.myOtherProperty = otherValue;}
//rest of your code...
}
Add <context:spring-configured /> to you application context file.
Then add the #Configurable annotation to Config class.
In my case in my unit test, executeScenarioRequest always is null
#RunWith(SpringRunner.class)
#ExtendWith(MockitoExtension.class)
class ScenarioServiceTestOld {
#Value("classpath:scenario/SampleScenario.json")
Resource executeScenarioRequest;
Change #ExtendWith(MockitoExtension.class) to #ExtendWith(SpringExtension.class)

How can I make properties in properties files mandatory in Spring?

I have an ApplicationContext.xml file with the following node:
<context:property-placeholder
location="classpath:hibernate.properties, classpath:pathConfiguration.properties" />
It specifies that both properties files will be used by my application.
Inside pathConfiguration.properties, some paths are defined, such as:
PATH_ERROR=/xxx/yyy/error
PATH_SUCCESS=/xxx/yyy/success
A PathConfiguration bean has setters for each path.
The problem is: when some of those mandatory paths are not defined, no error is thrown. How and where should I handle this problem?
The standard behaviour of the PropertyPlaceholder that is configured via <context:property-placeholder ... /> throws an exception when a property cannot be resolved once it is required in some place as long as you do not configure it otherwise.
For your case if you have a Bean that requires some properties like this, it will fail when the value cannot be resolved. For example like this:
public class PropertiesAwareBean {
#Value("${PATH_ERROR}")
private String errorPath;
String getErrorPath() {
return errorPath;
}
}
If you want to relax the PropertyPlaceholder and don't make it throw an Exception when a property cannot be resolved you can configure the PropertyPlaceholder to ignore unresolvable properties like this <context:property-placeholder ignore-unresolvable="true" ... />.
One way to reinforce the verification of parameters is to switch to a classical PropertyPlaceholderConfigurer bean in your beans file.
The PropertyPlaceholderConfigurer has properties which you can use to tweak its behavior and specify either an exception is thrown or not if some key is missing (take a look at setIgnoreUnresolvablePlaceholders or setIgnoreResourceNotFound).
If I remember correctly, in Spring 2.5, only the location attribute is supported for <context:property-placeholder> (things might have changed though).
I'm not sure if I fully understand your issue, but there are probably a variety of ways to approach this. One would be to make the paths mandatory by using constructor injection. In the constructor you could then validate the incoming values and if null for example, throw BeanInitializationException instances.

Categories

Resources