Spring - Injecting a list of dates from property file to a bean property [duplicate] - spring

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I specify values in a properties file so they can be retrieved using ResourceBundle#getStringArray?
I have a class like this:
public class BankHolidayCalendar {
List<DateTime> bankHolidays;
public BankHolidayCalendar(final List<DateTime> p_bankHolidays) {
bankHolidays = p_bankHolidays;
}
}
and a property file
# holidays.properties
holidayDates=01-01-2012, 13-02-2012, 22-04-2012
How can I read these dates from this property file and inject into the bean constructor?
I am using joda time here.

I would use the #Value annotation and create the DateTime object in the constructor like this:
public class BankHolidayCalendar {
List<DateTime> bankHolidays = new ArrayList<DateTime>();
public BankHolidayCalendar(#Value("holidayDates") String[] p_bankHolidays) {
for (String date : p_bankHolidays) {
bankHolidays.add(...);
}
}
}

Related

Can we declare a member variable as static for which we are doing constructor injection? [duplicate]

This question already has answers here:
Why can't we autowire static fields in spring?
(4 answers)
Can you use #Autowired with static fields?
(13 answers)
Closed 5 months ago.
To use a member variable in static function I need to declare that member variable as static. Is there anything wrong in declaring static fields and injecting them via constructor injection in multithreaded environment ?
#Named
public class QueryHelper {
// Anything wrong to declare it static and injecting it via constructor injection ?
private static QueryUtil queryUtil;
#Inject
QueryHelper(final QueryUtil queryUtil) {
this.queryUtil = queryUtil;
}
public static List<Contracts> getContracts() {
// .. some code
queryUtil.someFunction();
// ..some code
return contractList();
}
}

Error An object reference is required for the non-static field, method, or property 'gameManager.CompleteLevel()' [duplicate]

This question already has answers here:
Unity 5 An object reference is required for the non-static field, method, or property error
(2 answers)
Closed 3 years ago.
I'm taking a tutorial by Brackeys for a Unity Game and for some reason my code is returning this Error- An object reference is required for the non-static field, method, or property 'gameManager.CompleteLevel()'
here is some of the code/context
public class gameManager : MonoBehaviour
{
bool gameHasEnded = false;
public float restartdelay = 11f;
public void CompleteLevel()//here is the Error
{
Debug.Log("LEVEL COMPLETED");//printing this to make sure it works
}
public void gameEnd()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME OVER");
Invoke("Restart", 2f);//here making a delay
}
}
}
Error- An object reference is required for the non-static field, method, or property 'gameManager.CompleteLevel()' happens because you are trying to access something directly, without it being static or by not using a reference. You need to decide if you want this method, or class, to be static or create a reference to it.
You only need to do this to make it static
public static void CompleteLevel()//here is the Error
{
Debug.Log("LEVEL COMPLETED");//printing this to make sure it works
}

Error while using parameter in #Scheduled in a spring 4.1 application

I have Spring 4.1 Application. I am trying to schedule based on value from property file. I have read this post. But I do not want the following way of EL inside #Scheduled
#Scheduled(fixedDelayString = "${my.fixed.delay.prop}")
public void readLog() {
...
}
Here is my class.
public class MyService {
#Value("${timerInMilliSeconds: 60000}")
private long timerinMilliSeconds;
public myService(){
}
#Scheduled(fixedRate = timerinMilliSeconds)
public void myTimer() {
//do stuff
}
}
I get this error.
The value for annotation attribute Scheduled.fixedRate must be a constant
expression
You can't do that; it's a limitation of the way annotations work - Strings in annotations have to be constants (they are stored in the class and can't be different for each instance).
By the way ${my.fixed.delay.prop} is not "EL", it's a property placeholder.

Is it possible to have non String type values in a Spring Environment PropertySource

I'm trying to add ConfigSlurper's ConfigObjectinto an application context Environment in order to provide configuration values to the context.
The MapPropertySorce itself only expects its values to be of type Object only. But in the end property resolution fails as the EnvironmentAccessor will try to cast each ConfigObject to String.
So basically the question is, is there support for non String property resource values? Any supporting classes there (different EnvironmentAccessor?)
class ConfigSlurperLearningSpec extends Specification {
def configurationResource = new ClassPathResource("/META-INF/de.troi/application.configuration")
ConfigObject configuration = new ConfigSlurper().parse(configurationResource.getURL())
def "use as application context property source"() {
expect:
AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext()
context.register(PropertySourceInjection)
context.getEnvironment().getPropertySources().addLast(new MapPropertySource("mapConfiguration", configuration))
context.refresh()
String configuredValue=context.getBean('testBean')
configuredValue=='create'
}
}
#Configuration
class PropertySourceInjection {
#Value("#{environment['entityManagerFactory']['jpaPropertyMap']['hibernate.hbm2ddl.auto']}")
Object hibernateHbm2ddlAuto;
#Bean
String testBean() {
return new String(hibernateHbm2ddlAuto.toString())
}
}
It is definitely possible to inject non-string objects via ConfigSlurper.
Take a look at (shameless plug) https://github.com/ctzen/slurper-configuration

Spring Data Neo4j: Converter of object to string works, but object to long is not executed

I have a really strange issue with converting from domain objects to those Neo4j can natively store as property value. As a test case I use Joda's DateTime. A object of that type can be converted to a String or Long quite easily.
The conversion from DateTime to String works flawlessly with this code:
public class DateTimeToStringConverter implements Converter<DateTime, String> {
#Override
public String convert(DateTime source) {
return source.toDateTimeISO().toString();
}
}
The property shows up in the node:
Node[1] {
'__type__' = '...',
'entityEditedAt' = '2012-12-28T12:32:50.308+01:00',
'entityCreatedAt' = '2012-12-28T12:32:50.297+01:00',
...
}
However if I like to save the DateTime as Long (useful to sort by time in Cypher), it does not work at all. Here is my converter:
public class DateTimeToLongConverter implements Converter<DateTime, Long> {
#Override
public Long convert(DateTime source) {
return source.toDateTimeISO().getMillis();
}
}
The property is not saved on the node. Thus it is missing completely. No exception is thrown. It seems like the conversion code is not called at all.
The converters are hooked to Spring Data using code based configuration:
#Bean
public ConversionServiceFactoryBean conversionService() {
Set converters = Sets.newHashSet();
// These work!
converters.add(new DateTimeToStringConverter());
converters.add(new StringToDateTimeConverter());
// These don't :-(
//converters.add(new DateTimeToLongConverter());
//converters.add(new LongToDateTimeConverter());
ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
bean.setConverters(converters);
return bean;
}
Any clues? I'm quite lost here, as it should work in my opinion...
Edit
I found following text in the Spring Data Neo4j documentation:
All fields convertible to a String using the Spring conversion services will be stored as a string.
Does this mean, that only conversions to string are supported? This seems rather limiting.
Tell SDN that you want to store your joda DateTime property as a long with:
#NodeEntity
public class MyEntity {
...
#GraphProperty(propertyType = Long.class)
private DateTime timestamp;
....
}
Then your registered DateTimeToLongConverter will kick in.

Resources