XxxxxPersistence null pointer #BeanReference annotation - spring

I try to use the method public XxxxxLocalService getXxxxxLocalService() from xxxxxlocalServiceBaseImpl.java class which was generated by the service builder but I get a null value in the variable xxxxxLocalService!
public xxxxxLocalService getClientLocalService() {
return xxxxxLocalService;
}
this variable is instantiated by the #BeanReference annotation as we can see at the head of the java file:
#BeanReference(type = xxxxxLocalService.class)
protected XxxxxLocalService xxxxxLocalService;
#BeanReference(type = XxxxxPersistence.class)
protected XxxxxPersistence xxxxxPersistence;
the ServieBaseImpl package contains services with #BeanReference annotations that are processed by BeanReferenceAnnotationBeanPostProcessor that uses one of BeanLocators.
I noticed that there is a chicken & egg problem. You cannot load these beans without BeanLocator that is already populated with application context containing #BeanReferenced beans.
But you cannot create application context for BeanLocator to be populated with, because if you do so and BeanReferenceAnnotationBeanPostProcessor is part of the context, it will use BeanLocator that is not initialized.
BeanReferenceAnnotationBeanPostProcessor is declared in base-spring.xml that needs to be loaded with other bean definitions (from portlet-spring.xml etc.), because they depend on each other.
I don't know why this class can't set the variable value? in fact I'm not using the base-spring.xml in my configuration .. so I'm asking which lines I have to add in my ressource file for being able to use the bean reference annotation!!
Thanks

Related

Replacing micronaut's default KafkaProducerFactory with custom factory implementation

I need to customize the default KafkaProducerFactory (or any other default factory, say KafkaConsumerFactory) that ships with micronaut-kafka dependency. For that I tried to replace the existing factory using,
#Factory
#Replaces(factory = KafkaProducerFactory.class)
class CustomFactory extends KafkaProducerFactory {
#Bean
#Any
public <K, V> Producer<K, V> getProducer(
#Nullable InjectionPoint<KafkaProducer<K, V>> injectionPoint,
#Nullable #Parameter AbstractKafkaProducerConfiguration<K, V> producerConfiguration) {
validate(producerConfiguration); //this is my primary intension
super.getProducer(injectionPoint, producerConfiguration);
}
}
But it seems that Micronaut is not able to replace KafkaProducerFactory hence both the factory exists and I am getting error saying
"multiple candidate bean exists [CustomFactory, KafkaProducerFactory]"
I also thought to exclude the KafkaProducerFactory while the application loads, but could not find anything similar to Spring's ComponentScan.excludeFilter in Micronaut.
Is there anything wrong in my configuration or is there any other way to achieve the same?
Finally I got the answer. Let me elaborate little more for the actual context,
Problem
We have custom way of creating producer/consumer instances i.e. a custom class that creates those given the config properties. Now I had to modify the default factories so that instead of creating the instances on its own, the factory should invoke our custom class to instantiate producer/consumers.
Solution
I had to add #Primary along with other annotations and its working,
#Factory
#Replaces(factory = KafkaProducerFactory.class)
#Primary
class CustomFactory extends KafkaProducerFactory {
//code here
}
But the way I acheived this is kind of a work around because,
my primary intension was to override the producer/consumer creation part of default factory in a sub class and then replacing the default factory by the sub class. But as per the code structure in default factory class, it was not a single place where we can plug our custom code (no specific public method present consolidating the code for creating producer/consumer, it was being created from 3 separate places with "new") to create the producer. Hence we had to copy the entire default factory class and replaced the 3 places with custom code which does not seem to be a correct way.

#autowire beans and #value properties after object mapper deserialized json

I am using spring framework.
I am using objectMapper to desiriale store.json file:
service:
objectMapper.readValue(new File(jsonFilePath), Store.class)
store.json:
{
"type": "Store",
"name": "myStore",
}
Store.class:
#Value("${store.size:1000}")
private Integer sroreSize;
#autowire
private storePersistency storePersistency;
public Store(#JsonProperty("name") String name) {
super(name);
}
I am trying find out how to #autowire beans and #value properties in store.class, beans and properties that exist in applicationContext.
In current example sroreSize and storePersistency still null.
I know that I can inject fields to object mapper and then use #JacksonInject annotation but I have a lot of field to inject - not a good option for me.
Custom desirializer also not a good option for me.
Is there any way not to use custom desirializer or not to inject every bean/property that I need in store.class?
Something that injects all the beans and properties and I simply can use it in Store.class.
So you want some Store fields like storePersistency and sroreSize to be initialized once at application startup (which is when Spring will setup the application context) and then at runtime create multiple different Store objects differing in some fields as name that are initialized by Jackson.
I suggest annotating Store with #Component to get Spring to initialize #Value and #Autowired fields. The #Scope annotation will cause a new independent Store instance to be created each time. Simplified example:
#Component
#Scope(SCOPE_PROTOTYPE)
class Store {
private String name;
#Value("${store.size:1000}")
private Integer sroreSize;
}
Then the key is method readerForUpdating where you can pass an existing instance of Store and Jackson will update that instead of creating a new one as usually:
Store store = context.getBean(Store.class);
objectMapper.readerForUpdating(store).readValue("{\"name\":\"myStore\"}");
Where context is a Spring ApplicationContext reference that I autowired in a test class. You don't need to use the return value of readValue in this case, just inspect the existing store variable and name will be updated.

Multiple Constructor injection using Java Annotations

The SPRING doc says the following
Spring Framework 4.3, an #Autowired annotation on such a constructor
is no longer necessary if the target bean only defines one constructor
to begin with. However, if several constructors are available, at
least one must be annotated to teach the container which one to use.
As i understand if there are multiple constructors and we have not annotated any of them then i will get an error . I ran the following code
#Component // this is bean id
public class TennisCoach implements Coach {
private FortuneService fortuneservice;
public TennisCoach(FortuneService thefortuneservice) {
System.out.println(" inside 1 arg constructter");
fortuneservice = thefortuneservice;
}
public TennisCoach() {
System.out.println(" inside 0 arg constructter");
}
I call that using the below code
TennisCoach theCoach = myapp.getBean("tennisCoach", TennisCoach.class);
But i didn't get the error .I got the O/P as
inside 0 arg constructter
Why?
It looks like the text you've quoted from the Spring docs doesn't apply to a case where one of the constructors is a no-args (default) constructor. You can see this very easily if you try and add an bean reference parameter to it.
Spring attempts to determine the candidate constructors using AutowiredAnnotationBeanPostProcessor and in your scenario, will not find any single or autowired constructor, so it will record the no-args one and instantiate it in SimpleInstantiationStrategy.

Spring return dynamic instance based of String value

Java Spring question:
I have a interface MyInterface with one method
void exec (String str);
I have many implementation of MyInterface, say Oneimpl, anotherimpl yetanotherimpl...and so on and can keep adding new implementations.
how do I obtain an instance of a specific implementation using just the name of the implementing class passed as a STRING value , say "someRandomImpl"
The code should be dynamic and can provide a instance of new implementations without code change.
implements ApplicationContextAware
it will autowired ApplicationContext object
use the object like
context.getBean(beanName)
then you get the bean

i18n translation in JSP custom tag

Is it possible to write a custom JSP tag to take an i18n message key and output the translation phrase for the given request?
Normally in JSP/JSTL, I do:
<fmt:message key="${messageKey}"><fmt:param>arg1</fmt:param></fmt:message>
And I get the translation phrase. Now I need to do the following (there's a good reason for this):
<custom:translate key="${messageKey}" arg="arg1"/>
But I don't know how to look up the translation in the custom tag code. The TagSupport base class provides a pageContext from which I can get a ServletRequest which has the Locale... but how do I then look up the translation for a key?
I use Spring 3.0 and in my application-context.xml, I've defined a ReloadableBundleMessageSource so I can call:
messageSource.getMessage(
key, new Object[] {arg}, pageContext.getRequest().getLocale()
);
but I don't think I can inject messageSource into a custom tag, can I? Otherwise I can instantiate a new one, but would it load my tens of thousands of translations for every call? I don't want to resort to making messageSource a static member of a static class.
I don't do Spring, but in "plain" JSP you can just put the ResourceBundle instance in the session scope with help of a Filter or Servlet
ResourceBundle bundle = ResourceBundle.getBundle(basename, request.getLocale());
request.getSession().setAttribute("bundle", bundle);
And treat it in JSP like any other bean in EL.
${bundle[messageKey]}
It must be possible to have Spring to put that as a bean in the session scope.
There is a utility in spring to access the web application context. Then you can look up a bean by its name or type.
To get hold of your resource bundle, you could do something like:
WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
messageResource = springContext.getBean("messageResource");
This question is very old but I think it is worth to share another way to solve this.
To access the Spring message source in a custom tag you only need to extend the class org.springframework.web.servlet.tags.RequestContextAwareTag instead of TagSupport.
In this case you have to implement the method doStartTagInternal() instead of doStartTag(), but inside this method you will have access to the MessageSource through getRequestContext().getMessageSource() method.
Therefore, your class would look like:
public class CreateCustomFieldTag extends RequestContextAwareTag{
//variables (key, arg...), getters and setters
#Override
protected int doStartTagInternal() throws Exception {
getRequestContext().getMessageSource().getMessage(
key, new Object[] {arg}, getRequestContext().getLocale());
}
}

Resources