Spring MVC How can i use multiple property file - spring-mvc

I am using single .property file as
#PropertySource("classpath:messages.properties")
public class BasicController {
#Autowired
Environment env;
.....
...
}
How can i use multiple property file. I saw THIS but its not using #PropertySource

If you are using spring 4.0, you can use this annotation
#PropertySources(value = {#PropertySource("classpath:/app.properties")})
or if you are using spring 3.0+,
you can use either mention the configuration in config file like below or call the setLocations method in your class directly.
In the latter case, you will not require to use the PropertySource annotation.
<bean id="propertiesPlacholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
<property name="locations">
<list>
<value>classpath:/app1.properties</value>
<value>classpath:/app2.properties</value>
</list>
</property>
</bean>
you can use property in those files as below
#Controller
public class BasicController {
#Value
String name;
.....
...
}
if name is available as key in property file..it will be injected here..

You can either use #PropertySources like
#PropertySources(value = {#PropertySource("classpath:jdbc.properties"),#PropertySource("classpath:paypalConfig.properties")})
Or you can use #PropertySource like
#PropertySource(value{"classpath:jdbc.properties","classpath:paypalConfig.properties"})
Once you do this you can access values corresponding a key in the property files using Environment variable like so
environment.getProperty("YOUR_KEY_IN_PROPERTY_FILE");

Related

Customizing Hybris accelerator storefront controllers in an addon

I'm using Hybris 6.3 and would like to follow the best practice of customizing the accelerator storefront controllers using an addon. This is done to make upgrading to a newer storefront much easier.
For example, the accelerator defines a Minicart controller similar to
package com.custom.storefront.controllers.misc;
#Controller
public class MiniCartController extends AbstractController
{
#RequestMapping(value = "/cart/miniCart/{totalDisplay:.*}", method = RequestMethod.GET)
public String getMiniCart(#PathVariable final String totalDisplay, final Model model)
{
//default functionality
}
}
In my addon, I would like to map that same URL pattern to a new controller that will override the functionality.
package com.custom.storefrontaddon.controllers.misc;
#Controller
public class MyCustomMiniCartController extends AbstractController
{
#RequestMapping(value = "/cart/miniCart/{totalDisplay:.*}", method = RequestMethod.GET)
public String getMiniCart(#PathVariable final String totalDisplay, final Model model)
{
//overriding functionality, different from the default accelerator storefront
}
}
This question has been asked here, and the accepted advice was to do as follows:
In addon-web-spring.xml, override the controller bean like
<bean name="miniCartController" class="com.custom.storefrontaddon.controllers.misc.MyCustomMiniCartController"/>
In addon-web-spring.xml, add a SimpleUrlHandlerMapping like
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/cart/miniCart/**">miniCartController</prop>
</props>
</property>
</bean>
The addon controller will now be called instead of the default accelerator controller for the target URL.
My Question
How does this mechanism work when the Spring documentation explicitly says that
There are also several things no longer possible:
- Select a controller first with a SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping and then narrow the method based on #RequestMapping annotations.
Spring is using RequestMappingHandlerMapping by default in the accelerator storefront, and in the addon we are introducing SimpleUrlHandlerMapping. I want to understand why this works, when every other forum post I've read says that you cannot override #RequestMapping URLs in a different controller, or you will get an exception thrown for the duplicate URL.
In my answer, I will suppopse that you made a typo, and you meant MyCustomMiniCartController instead of MiniCartController in:
<bean name="miniCartController" class="com.custom.storefrontaddon.controllers.misc.MyCustomMiniCartController"/>
The thing here is that SimpleUrlHandlerMapping has nothing to do and its declaration in
addon-web-spring.xml is completely useless.
Redefining the miniCartController bean in the addon makes the bean definition overridden by the addon class, and so the request mapping that is declared in the addon class is the one "used" by the RequestMappingHandlerMapping.

Spring Data Rest: Entity serialization with LAZY object cause JsonMappingException

I'm getting the following Exception with a Spring Data Rest project:
com.fasterxml.jackson.databind.JsonMappingException:
No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
(through reference chain: org.springframework.data.rest.webmvc.json.["content"]->test.spring.data.rest.xml.entities.Author_$$_jvstb93_1["handler"])
Certainly, I have some entities that have the fetch configuration = FetchType.LAZY.
I followed many instructions and links, but I still have this exception.
What I have already tried to do (with NO effetcs):
add #EnableHypermediaSupport(type = HypermediaType.HAL) in a config class that extends RepositoryRestMvcConfiguration
#Override configureJacksonObjectMapper in the same class, with also using Jackson2DatatypeHelper.configureObjectMapper():
#Override
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
Jackson2DatatypeHelper.configureObjectMapper(objectMapper);
}
add a "org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter" filter in the web.xml
create a custom class that extends ObjectMapper, with this constructor:
public HibernateAwareObjectMapper() {
Hibernate5Module hm = new Hibernate5Module();
registerModule(hm);
}
and this config:
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="test.spring.data.rest.xml.config.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
No one of the actions above has solved the problem!
How to (definitely) solve this problem?
Thanks.
I have found the solution to this annoying problem.
For every repository of the Spring Data Rest application it has to be defined a custom #Projection; in the projection there will be the necessaries fields.
Pay attention that if there are cycylc references between two entities, the corrispective methods of the projections have to be annotated with #JsonBackReference annotation (for #ManyToOne annotated fields) and with #JsonManagedReference annotation (for #OneToMany annotated fields), otherwise there will be a JSON loop in the JSON serialization.
In every #Repository annotation (or #RepositoryRestResource annotation) it has to be marked the excerptProjection property, with the custom projection.
With this management, there is no need of any other configuration, and the exception for Lazy objects finally is vanished.

Run-Time Configuring a Hibernate Validation Annotation

I have some business validation logic of the form "X is valid IFF Service Y returns Z", where X and Z are known at compile time, and Y's location is loaded from a Spring configuration file.
I'd like to use JSR-303 annotation-based validation, together with the Spring config, so I can write code like the following:
Custom class level constraint annotation:
#MyValidation
public class X { .... }
ConstraintValidator for #MyValidation:
public class MyValidationValidator implements ConstraintValidator<MyValidation, X> {
private MyService service;
public MyService getService() { return service; }
public void setService(MyService serv) { this.service = serv; }
//Validation Logic...
}
Spring config:
<bean id="ServiceY" class="...">
...
</bean>
<bean id="mvv" class="MyValidationValidator">
<property name="service" value="ServiceY" />
</bean>
But my attempts at combining these in that fashion are failing, as the validator's property is not getting set.
Right now, I'm using Spring AOP Interceptors as a workaround, but that's not ideal in my mind.
One of the other questions here, made me think of using a properties file/property, but wouldn't that require me to repeat the service's configuration?
Another mentioned defining the constraint mapping programmatically, but if I'm doing that, I'm probably better-off with my workaround.
Any clues on how to do that dynamic configuration?
You should use Spring's LocalValidatorFactoryBean to set up a Bean Validation validator:
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
A validator set up that way will internally use a ConstraintValidatorFactoryimplementation that performs dependency injection on the created validator instances, just mark the service field in your validator with #Inject or #Autowired. Note that it's not required to set up the constraint validator itself as Spring bean.
You can find more details in the Spring reference guide.

How to add custom error messages in Hibernate validator

I have a simple class like this,
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
public class Form implements Serializable {
#NotNull
#Length(min = 2, max = 20)
private String lastName;
}
I have messages.properties file in the classpath. It's then loaded via Spring bean as follows,
<bean name="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource">
<ref bean="resourceBundleLocator"/>
</property>
</bean>
<bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath*:messages.properties</value>
</list>
</property>
</bean>
All I want is to get error messages customized according to the bean validated. In other words I want to have each ConstraintViolation object return the error message I have defined in my property file instead of the default one. Is it possible to add message property with a value like this format {xxx.yyyy.zzzz} and refer that message from the messages.properties file ?
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Form>> inputErrors = validator.validate(form);
If I want to customize the default message for #NotNull and #Length, how can I do that?
My experience on Hibernate validation is zero, Any sample code or step by step guide would be appreciated.
You have this resource bundle file holding the message values.
I think you have to use the path to the i.e. #NotNull annotation
to override the message by hand!
like javax.validation.constraints.NotNull=Notnull error happened!
or something like that!
Look here for that :
Hibernate Validator - The error message
Hope that helps

Externalize #InitBinder initialization into WebBindingInitializer

There are two major means of data binding initialization, but there is a drawback in the oldschool one, that I can't figure out. This annotation way is great :
#InitBinder("order")
public void initBinder(WebDataBinder binder) {
// Problem is that I want to set allowed and restricted fields - can be done here
binder.setAllowedFields(allowedFields.split(","));
}
but I can't be done with ConfigurableWebBindingInitializer. First off, the binder instance is created in AnnotationMethodHandlerAdapter and initializer is passed the binder instance somewhere in HandlerMethodInvoker so I can't set it up... I can't do something like this :
<bean id="codesResolver" class="org.springframework.validation.DefaultMessageCodesResolver" />
<bean id="binder" class="org.springframework.web.portlet.bind.PortletRequestDataBinder" scope="prototype">
<property name="allowedFields" value="${allowedFields}" />
<aop:scoped-proxy />
</bean>
<bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="messageCodesResolver" ref="codesResolver" />
</bean>
Because binder instance is passed into it in handlerAdapter. How can I set up the binder then ?
There is no way of setting it up in xml configuration. You must implement your custom WebBindingInitializer ... The ConfigurableWebBindingInitializer is obviously missing the possibility of setting up allowed and restricted fields...
Or you can vote up SPR-8601
This is very old, however for anyone that dislike the use of annotations in production code (like me) here is a solution I found to add a init binder without use of annotations. You only need to overwrite initBinder method that extends from most of base controllers provided by Spring:
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
{
System.out.println("Binding!!!!!");
super.initBinder(request, binder);
binder.registerCustomEditor(Double.class, new CurrencyPropertyEditor());
}
Where my CurrencyPropertyEditor class is a subclass of java.beans.PropertyEditorSupport with getAsText, getValue, setValue and setAsText methods overwrited as well.
Hope it helps!!!

Resources