Update field annotated with #Value in runtime - spring

Let's imagine we have such a component in Spring:
#Component
public class MyComponent {
#Value("${someProperty}")
private String text;
}
If we define the property placeholder:
<context:property-placeholder location="classpath:myProps.properties"/>
And myPropos.properties contains the value for someProperty the value will be injected to the text field when the context is initialized. That's quite simple and easy.
But let's say that I have a service that enables user to change the value of the someProperty:
public void changeProp(String name, String newValue);
Is there a chance I can re-inject the newValue to text field. I mean it should be quite straight forward.. Basically it's nothing different than the after-initialization injection. I can not imagine that Spring does not have support for this? Can I fire some event or something?
I could do this on my own basically, but I wander is it maybe something there already? If not does anyone know what Spring class is in fact handling the injections at the first place? I could probably reuse the code there do perform this on my own if a solution does not exists.

I expect spring does not have a support for this, because the normal injection is done while creating the bean, but not will it is put in service.
Anyway: in this blog entry "Reloadable Application Properties with Spring 3.1, Java 7 and Google Guava", you can find the idea for an solution.
The key idea is to use a post processor to build a list of all fields with property fields. And if the properties are changed on can use this list to update the fields.

Related

How to change Jackson to detect all fields in a POJO, other than only public ones?

When using Spring Boot for a project, Jackson came as default to serialize objects back and from Jsons. I realize that Jackson fails if you don't have public accessors, e.g., getters/setters, or public fields in your POJO.
The behavior is different when I switch to Gson. It detects all fields regardless of their visibility. For this reason, I ended up using Gson.
I felt a little uncomfortable about switching my POJO access rules; It would force some refactoring in the project structure.
So, no problems using Gson, but is there a way of change Jackson's behavior?
Jackson does support reading values from private member fields, but does not do it by default.
You can configure the behavior globally in the Spring Boot config like
jackson:
visibility.field: any
visibility.getter: none
visibility.setter: none
visibility.is-getter: none
(this config will only look for member fields and no longer check get, set and is methods)
You could also use the #JsonAutoDetect annotation to do the same setting for a specific class.
Try to set visibility at ObjectMapper level,
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

Are Thymeleaf model attributes not allowed to start with 'is'?

So I'm writing a springboot application and came across a weird behaviour: If a property name start with is, for example: isIgnoreRequest thymeleaf won't find it but if i change it to ignoreRequest it works.
So my question is: Am I not allowed to have is at the beginning?
Here is some more context:
data class Response(val isIgnoreRequest: Boolean = false,
val name: String = StringUtils.EMPTY)
...
//This is how I add the attribute
//Info = Response object
redirectAttributes.addFlashAttribute(ATTRIBUTE_RESPONSE, info)
With the code above thymeleaf can't find the property:
Property or field 'isIgnoreRequest' cannot be found on object of type ... - maybe not public or not valid?
If I remove the is it works fine. Even though it sounds stupid I think the is is indeed my problem.
Yes, the model attributes can start with is. The issue isn't coming from thymeleaf, but from kotlin (nice job putting it in the tags). Let me explain:
When you reference a model attribute in thymeleaf, it looks for the getter/setter method of that attribute using the normal convention; in your example, for the attribute isIgnoreRequest, thymeleaf will look for the methods getIsIgnoreRequest and setIsIgnoreRequest.
What happens is kotlin generates the getters and setters for isXXX booleans in a different way than the standard, and thymeleaf fails when calling them with the standard syntax. You can see more on how kotlin generates the getters and setters for booleans in
https://github.com/sockeqwe/fragmentargs/issues/46 or
https://github.com/sockeqwe/sqlbrite-dao/issues/27
As to solve your issue, the best solution is probably naming your attributes in a different way so that kotlin doesn't mess with the standard for generating getter and setter methods (which IMO only complicates things unnecessarily; although some frameworks like JSF had a similar issue with isXXX booleans since forever).

How to add a custom ContentHander for JAXB2 support in Spring 3 (MVC)?

Scenario: I have a web application that uses Spring 3 MVC. Using the powerful new annotations in Spring 3 (#Controller, #ResponseBody etc), I have written some domain objects with #XML annotations for marhalling ajax calls to web clients. Everything works great. I declared my Controller class to have a return type #ResponseBody with root XML object - the payload gets marshalled correctly and sent to Client.
The problem is that some data in the content is breaking the XML compliance. I need to wrap this with CDATA when necessary. I saw a POST here How to generate CDATA block using JAXB? that recommends using a custom Content Handler. Ok, fantastic!
public class CDataContentHandler extends (SAXHandler|XMLSerializer|Other...) {
// see http://www.w3.org/TR/xml/#syntax
private static final Pattern XML_CHARS = Pattern.compile("[<>&]");
public void characters(char[] ch, int start, int length) throws SAXException {
boolean useCData = XML_CHARS.matcher(new String(c,start,length)).find();
if (useCData) super.startCDATA();
super.characters(ch, start, length);
if (useCData) super.endCDATA();
}
}
Using Spring MVC 3, how do I achieve this? Everything was "auto-magically" done for me with regards to the JAXB aspects of setup, Spring read the return type of the method, saw the annotations of the return type and picked up JAXB2 off the classpath to do the marshalling (Object to XML conversion). So where on earth is the "hook" that permits a user to register a custom Content Handler to the config?
Using EclipseLink JAXB implementation it is as easy as adding #XmlCDATA to the Object attribute concerned. Is there some smart way Spring can help out here / abstract this problem away into a minor configuration detail?
I know Spring isn't tied to any particular implementation but for the sake of this question, please can we assume I am using whatever the default implementation is. I tried the Docs here http://static.springsource.org/spring-ws/site/reference/html/oxm.html but it barely helped at all with this question from what I could understand.
Thanks all for any replies, be really appreciated.
Update:
Thanks for the suggested answer below Akshay. It was sufficient to put me on right tracks. Investigating further, I see there is a bit of history with this one between Spring version 3.05 and 3.2. In Spring 3.05 it used to be quite difficult to register a custom MessageConverter (this is really the goal here).
This conversation pretty much explains the thinking behind the development changes requested:
https://jira.springsource.org/browse/SPR-7504
Here is a link to the typically required class override to build a cusom solution:
http://static.springsource.org/spring/docs/3.1.0.M1/javadoc-api/org/springframework/http/converter/AbstractHttpMessageConverter.html
And the following Question on stack overflow is very similar to what I was asking for (except the #ResponseBody discussion relates to JSON and jackson) - the goal is basically the same.
Spring 3.2 and Jackson 2: add custom object mapper
So it looks like usage of , and overriding MarshallingHttpMessageConverter is needed, registering to AnnotationMethodHandlerAdapter. There is a recommended solution in link above to also get clever with this stuff and wrap the whole thing behind a custom defined Annotation.
I haven't yet developed a working solution but since I asked the questions, wanted to at least post something that may help others with the same sort of question, to get started. With all due respect, although this has all improved in Spring 3.2, it's still bit of a dogs dinner to get a little customization working... I really was expecting a one liner config change etc.
Rather than twist and bend Spring, perhaps the easiest answer for my particular issue is just to change JAXB2 implementation and use something like Eclipse Link JAXB that can do this out of the box.
Basically you need to create a custom HttpMessageConverter. Instead of relying on the Jaxb2RootElementHttpMessageConverter that spring uses by default.
Unfortunately, customizing one converter means you are telling spring that you will take care of loading all the converters you need! Which is fairly involved and can get complicated, based on whether you use annotations, component scanning, Spring 3.1 or earlier, etc.. The issue of how to add a custom converter is addressed here: Custom HttpMessageConverter with #ResponseBody to do Json things
In your custom message converter you are free to use any custom JAXB2 content handlers.
Another, simpler approach to solve your original problem would be to use a custom XmlJavaTypeAdapter. Create a custom implementation of javax.xml.bind.annotation.adapters.XmlAdapter to handle CDATA, in the marshal method wrap the return value with the cdata braces. Then in your mapped pojo, use the XmlAdapter annotation, pass it the class of your custom adapter and you should be done.
I have not myself implemented the adapter approach, so couldn't provide sample code. But it should work, and won't be a lot of work.
Hope this helps.

Spring MVC request / command objects

Is there a convenient way to turn something like this..
#RequestMapping("/some/action/{q}/...")
public void doSomething(#PathVariable("q"), oh, my, god, a, billion, annotated parameters) { .. }
Into something like this..
#RequestMapping("/some/action/{q}/...")
public void doSomething(NiceEncapsulatingRequetObject request) { .. }
With Spring MVC?
After checking the docs, it doesn't seem like it is supported out of the box. You could try to create your own HandlerMethodArgumentResolver which gives you this feature. You might run into some issues since you'll need a circular reference between your implementation and the HandlerMethodArgumentResolverComposite instance. Nevertheless I think it should be possible.
Yes spring supports this out of the box, it is usualy refered to as bean binding.
Basicly you create an object with paramaters with the same name,
so if you have a paramater "q", your object should contain a private string q with both getter and setter present. It's also prefered not to use any constructors.
Spring will just fill in the paramaters it has in your object and pass it via the method's paramater.
You can create you own object like NiceEncapsulatingRequetObject and it's attributes should be String oh, Integer my etc. If you send the request with the exact names it will work

How to get property from context property placeholder tag inside custom java component

I have Mule Configuration that defines
<context:property-placeholder location="classpath:/mule-sw.properties"/>
And I also have a custom component class in Java which use #Lookup annotation on one of my field
#Lookup("file-path")
private String path;
Considering my "mule-sw.properties" is like this
file-path=C:/hello.txt
After I start up the Mule App, I always get Deploy Exception
org.mule.api.expression.RequiredValueException: "Required object not found in registry of Type "class java.lang.String" with name "file-path" on object "class component.CustomComponent"
I also tried to change the #Lookup("file-path") with #Lookup("${file-path}") with no success.
Anyone can give me a better solution ?
Any help is kindly appreciated.
Thanks
The #Lookup annotation is designed to retrieve objects from the registry , whereas what you are trying to do is to assign a value to an attribute of your custom component.
There are 2 way to do that:
1) Through property injection, i.e. you declare your component like the following:
<custom-component class="org.myCompany.CustomComponent">
<property name="file-path" value="${file-path}" />
</custom-component>
2) Through Spring EL support and the #Value annotation, i.e. you annotate your attribute in the following way
#Value("${file-path}")
private String path;
I'd recommend the first approach since it is easier to maintain from a flow perspective
#Value("#{'${file-path}'}")
private String path;
Give this a shot. I think you need to wrap it in an EL block #{} for it to be properly recognized.

Resources