Properties not being passed to bean - java

In the below code I'm getting a NullPointer at line private File ratesFile = new File(ratesFilePath); in my myClass.java.
As far as I can see my properties file is fine, I'm importing it fine into my .xml configuration and passing the property to my class OK. My getters and setters seem OK to me too. Any pointers on why my properties aren't being passed to my class?
Spring Batch 2.1.8
myClass.properties:
rates_file_path=/opt/rates
rates_file=rates.txt
myClass.xml:
<bean id="myClassProps" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:conf/myClass.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
<bean id="myClass" class="com.stuff.blah.myClass">
<property name="ratesFilePath" value="${rates_file_path}/${rates_file}" />
</bean>
myClass.java
public class myClass implements Tasklet, InitializingBean {
private String ratesFilePath;
private File ratesFile = new File(ratesFilePath);
public String getRatesFilePath() {
return ratesFilePath;
}
public void setRatesFilePath(String ratesFilePath) {
this.ratesFilePath = ratesFilePath;
}
}

In your myClass,
private File ratesFile = new File(ratesFilePath);
is an error raising code.
Both ratesFilePath and ratesFile is initialized when the constructor is called.
Because ratesFilePath does not have any values to initialize with, it is set to null.
And when ratesFile is trying to be initialized, it will use the ratesFilePath, which is null and will raise a NullPointerException.
To fix this, first set your ratesFile to null;
private File ratesFile = null;
And set ratesFile on the setter method of ratesfilePath after making sure that path is not null.
public void setRatesFilePath(String ratesFilePath) {
this.ratesFilePath = ratesFilePath;
if(ratesFilePath == null) ratesFile = null;
else ratesFile = new File(ratesFilePath);
}

Related

Spring bean creation failed. Can parameter type of the setter be parent of the return type of the getter?

I am facing this exception while creating bean of datasource from DBCP2. Exception is
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'connectionInitSqls' of bean class [org.apache.commons.dbcp2.BasicDataSource]: Bean property 'connectionInitSqls' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
here is my bean configuration
<bean id="fileStore_dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close" lazy-init="true">
<!-- Just that property which causes problem -->
<property name="connectionInitSqls">
<list>
<value>#{filestore.jdbc.connectionInitSql}</value>
</list>
</property>
</bean>
Here is the setter and getter code for connectionInitSqls in BasicDataSource class. version of DBCP2 is 2.1.1
private volatile List<String> connectionInitSqls;
public List<String> getConnectionInitSqls() {
final List<String> result = connectionInitSqls;
if (result == null) {
return Collections.emptyList();
}
return result;
}
public void setConnectionInitSqls(final Collection<String> connectionInitSqls) {
if (connectionInitSqls != null && connectionInitSqls.size() > 0) {
ArrayList<String> newVal = null;
for (final String s : connectionInitSqls) {
if (s != null && s.trim().length() > 0) {
if (newVal == null) {
newVal = new ArrayList<>();
}
newVal.add(s);
}
}
this.connectionInitSqls = newVal;
} else {
this.connectionInitSqls = null;
}
}
You can see that argument in setter is Collection which is Super type of List. But I dont know why spring could not instantiate the bean. Is this Spring problem or Bug in DBCP2 code. Can we give parent type of property in setter argument?
How can I resolve this problem? Any Help would be appreciated.
Spring will use reflection to find the setter property. So it will find the setter using setConnectionInitSqls and argument list because of the property type(which it will find from getter method getConnectionInitSqls) and it will not find therefore the exception.
Exception message is self explanatory now. Note that the property may not exist at all. Spring just works with getters and setters. It finds the appropriate setter method using the getter method's( which is easy to find just prefix with get and no arg method) return value type.
Bean property 'connectionInitSqls' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?`
you can try using MethodInvokingFactoryBean.
<bean id="fileStore_dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close" lazy-init="true">
</bean>
<bean id="customInjector"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="fileStore_dataSource" />
<property name="targetMethod">
<value>setConnectionInitSqls</value>
</property>
<property name="arguments">
<list>
<value>#{filestore.jdbc.connectionInitSql}</value>
</list>
</property>
</bean>
Alternative way:
I would prefer this as it is SAFER. Reason being all properties are set during the instantiation phase itself. And then wiring between the beans happen. In the previous case it may be error prone because setting connectionInitSqls happens at a different time and chances are that connections might have already been created(without looking into the internals of the implementation of BasicDataSource).
public class CustomBasicDataSource extends BasicDataSource{
public void setConnectionInitSqls(List<String> connectionInitSqls) {
super.setConnectionInitSqls(connectionInitSqls);
}
}
replace with this class in xml
<bean id="fileStore_dataSource"
class="org.company.somepackage.CustomBasicDataSource" destroy-method="close" lazy-init="true">
...<!-- rest remain same-->
</bean>
Try ${ instead of #{
<property name="connectionInitSqls">
<list>
<value>${filestore.jdbc.connectionInitSql}</value>
</list>
</property>

Spring AOP- Logging: Logs are not getting printed

I am new to Spring-AOP and trying to use it in my project. I have created a class implementing MethodBeforeAdvice :
public class LogBeforeCallAdvice implements MethodBeforeAdvice{
/* (non-Javadoc)
* #see org.springframework.aop.MethodBeforeAdvice#before(java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
*/
#Override
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("**CALLING METHOD - " + arg0.getName() + " IN BEFORE CALLING ADVICE**");
}
}
These are the entries my application-context.xml file:
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="logMethods"></property>
<property name="interceptorNames">
<list>
<value>beforeCall</value>
</list>
</property>
</bean>
<bean id = "logMethods" class = "com.MyPackage.LogMethods" lazy-init = "true" init-method="init">
<property name = "someProperty" ref = "someBeanReference"/>
</bean>
And in my main method, I am getting the proxy like this:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
LogMethods logMethods = (LogMethods)context.getBean("proxy");
After executing the above code, I am not getting the log written in before() method of Before Calling Advice. But I am able to see the sys outs mentioned in the LogMethods class and its property reference beans also.
I want to print the before advice logs for all the methods in LogMethods and its property beans' methods (without using aspectj annotations).
I am not getting any error also. What am I doing wrong? Can someone please help?
Thanks in Advance!!

Extract specific attribute from flat file item writer

I have an object returned from item processor.
public class PcdRateMapper
{
private Pcdrate pcdRate;
private Boolean isValidPcdRate;
public PcdRateMapper ()
{
// pcdRate = new Pcdrate ();
}
public Pcdrate getPcdRate ()
{
return pcdRate;
}
public void setPcdRate (Pcdrate pcdRate)
{
this.pcdRate = pcdRate;
}
public Boolean getIsValidPcdRate ()
{
return isValidPcdRate;
}
public void setIsValidPcdRate (Boolean isValidPcdRate)
{
this.isValidPcdRate = isValidPcdRate;
}
Now i want to extract only Pcdrate object values in my item writer. How can I do this. Currently I'm using following spring configuration but getting invalid property exception. Thanks in advance.
<
property name="lineAggregator">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="delimiter" value="," />
<property name=""></property>
<property name="fieldExtractor">
<bean
class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name=""></property>
<property name="names"
value="company, subcoy" />
</bean>
</property>
</bean>
</property>
The invalid property exception may stem from
<property name=""></property>
where the property name is an empty string. You have that twice in the code above, remove it.
Your xml structure seems to be invalid, see spring_bean_definition
to see how it should look like.
On the bean of type BeanWrapperFieldExtractor you must set the property 'names' to the names of properties that you want to extraxt, in your case 'pcdRate'.
It should be configured like this :
<bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="pcdRate" />
</bean>

Spring's #Autowired not injecting a Map - am I even using it correctly?

I'm trying to add some Spring configuration to an existing utility class. It doesn't seem to work and I'm not sure why (my first time using these Spring options, I'm not even sure I'm doing it correctly).
The class in question
#Configurable(autowire=Autowire.BY_NAME, preConstruction=true)
public class DataUtility
{
private static final DataUtility INSTANCE = new DataUtility();
#Autowired(required=true) //This is the new field and annotation
private Map<String,String> dataFileMapping = new HashMap<String, String>();
public static DataUtility getInstance()
{
return INSTANCE;
}
private DataUtility()
{
//Do a bunch of setup work here
for (String s : dataFileMapping)
{
addDataToCache(dataFileMapping(s))
}
}
The spring config looks like this:
<context:annotation-config/>
<context:spring-configured/>
<bean id="util" class="com.myCompany.DataUtility">
<property name="dataFileMapping">
<map>
<entry key="data1" value="data/file1.dat"/>
<entry key="data2" value="data/file2.dat"/>
<entry key="data3" value="data/file3.dat"/>
</map>
</property>
</bean>
The problem is that when I step through my code in the debugger, I can see that dataFileMapping is empty. I'm not even sure if the spring config is even running.
I think you just need to add getters and setters for dataFileMapping
Also, remember that you can't iterate through the map in the constructor, spring wouldn't have had a chance to set it until after the constructor executes.
In addition to this, you can't make your constructor private and expect spring to be able to instantiate it.
The root of your problem is that you seem to be using a static reference INSTANCE to access the object. Spring is making a bean named 'util' and setting it up with your data, but that isn't becoming the object that INSTANCE points to. The initialization of static fields happens when the class is first loaded, long before spring ever gets a chance to create and inject beans.
You can sort of fake it like this, but of course attempts to access instance before bean initialization will fail:
#Configurable(autowire=Autowire.BY_NAME, preConstruction=true)
public class DataUtility
{
private static final DataUtility INSTANCE = null;
#Autowired(required=true) //This is the new field and annotation
private Map<String,String> dataFileMapping = new HashMap<String, String>();
public static DataUtility getInstance()
{
return INSTANCE;
}
public postInit()
{
INSTANCE = this;
//Do a bunch of setup work here
for (String s : dataFileMapping)
{
addDataToCache(dataFileMapping(s))
}
}
<bean id="util" class="com.myCompany.DataUtility" init-method="postInit">
<property name="dataFileMapping">
<map>
<entry key="data1" value="data/file1.dat"/>
<entry key="data2" value="data/file2.dat"/>
<entry key="data3" value="data/file3.dat"/>
</map>
</property>
</bean>

Spring 3: disable SpEL evaluation of a bean property value?

We're in the process of updating our apps from Spring 2.5 to 3.0 and we've hit a problem with the new SpEL evaluation of bean properties.
We've been using an in-house templating syntax in one module which unfortunately uses the same "#{xyz}" markup as SpEL. We have a few beans which take string's containing these expressions as properties but spring assumes they are SpEL expressions and throws a SpelEvaluationException when it tries to instantiate the bean.
e.g.
<bean id="templatingEngine" class="com.foo.TemplatingEngine">
<property name="barTemplate" value="user=#{uid}&country=#{cty}"/>
</bean>
Is it possible to disable SpEL evaluation, ideally per-bean, but alternatively for the whole application context?
Alternatively is there a way to escape the values?
Thanks,
Stephen
Completely disable SpEL evaluation by calling the bean factory setBeanExpressionResolver method passing in null. You can define a BeanFactoryPostProcessor to do this.
public class DisableSpel implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory)
throws BeansException
{
beanFactory.setBeanExpressionResolver(null);
}
}
Then define this bean in the application context.
<bean class="com.example.spel.DisableSpel"/>
Well what you could do is re-define the expression language delimiters.
I would say the way to do this is through a special bean that implements BeanFactoryPostProcessor (thanks to inspiration by Jim Huang):
public class ExpressionTokensRedefiner implements BeanFactoryPostProcessor{
private BeanExpressionResolver beanExpressionResolver;
public void setBeanExpressionResolver(
final BeanExpressionResolver beanExpressionResolver){
this.beanExpressionResolver = beanExpressionResolver;
}
#Override
public void postProcessBeanFactory(
final ConfigurableListableBeanFactory beanFactory)
throws BeansException{
beanFactory.setBeanExpressionResolver(createResolver());
}
private String expressionPrefix = "${";
private String expressionSuffix = "}";
public void setExpressionPrefix(final String expressionPrefix){
this.expressionPrefix = expressionPrefix;
}
public void setExpressionSuffix(final String expressionSuffix){
this.expressionSuffix = expressionSuffix;
}
private BeanExpressionResolver createResolver(){
if(beanExpressionResolver == null){
final StandardBeanExpressionResolver resolver =
new StandardBeanExpressionResolver();
resolver.setExpressionPrefix(expressionPrefix);
resolver.setExpressionSuffix(expressionSuffix);
return resolver;
} else{
return beanExpressionResolver;
}
}
}
Define it as a bean like this:
<bean class="foo.bar.ExpressionTokensRedefiner">
<property name="expressionPrefix" value="[[" />
<property name="expressionSuffix" value="]]" />
</bean>
or like this:
<!-- this will use the default tokens ${ and } -->
<bean class="foo.bar.ExpressionTokensRedefiner" />
or use a custom resolver:
<bean class="foo.bar.ExpressionTokensRedefiner">
<property name="beanExpressionResolver">
<bean class="foo.bar.CustomExpressionResolver" />
</property>
</bean>
Now you can leave your definitions untouched and if you want to use SpEL, use the new delimiters.
EDIT: now I did test it and it actually works.
<bean class="foo.bar.ExpressionTokensRedefiner">
<property name="expressionPrefix" value="[[" />
<property name="expressionSuffix" value="]]" />
</bean>
<bean class="foo.bar.FooFritz">
<property name="fizz" value="[[ systemProperties['user.home'] ]]"></property>
<property name="fozz" value="[[ systemProperties['java.io.tmpdir'] ]]"></property>
<!-- this is what it would normally choke on -->
<property name="fazz" value="#{ boom() }"></property>
</bean>
Test code:
final ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("classpath:foo/bar/ctx.xml");
context.refresh();
final FooFritz fooFritz = context.getBean(FooFritz.class);
System.out.println(fooFritz.getFizz());
System.out.println(fooFritz.getFozz());
System.out.println(fooFritz.getFazz());
Output:
/home/seanizer
/tmp
#{ boom() }
I am not a dab, but this mighbe of help.
https://issues.apache.org/jira/browse/CAMEL-2599

Categories