19 April 2016

Spring's @Value with custom types

Everyone knows you can do:
@Value("${some.property}") String myString;
@Value("classpath:/${some.file}") Resource file;
Some know you can also do:
@Value("classpath:/myFile.txt") InputStream inputStream;
@Value("classpath:/${some.property}") Reader reader;
But what if we want to do:
@Value("some string ${with.properties}") MyObject myObject;
In this case spring will automatically look for builder methods valueOf, of, from or proper constructor (as described in ObjectToObjectConverter). So
public MyObject(String parameter) {...}
will be enough.

If more complex conversion is needed, one possibility is to create a bean named conversionService and type ConversionService with registered converters. For example:
@Bean(name="conversionService")
public ConversionService conversionService() {
    DefaultConversionService conversionService = new DefaultConversionService();
    conversionService.addConverter(String.class, MyObject.class, s -> ...);
    return conversionService;
}

Tested with spring 4.2.5.RELEASE

10 January 2016

Remote git branch with different name

Sometimes we want to publish one of our local branches as a master branch in a new git repository.

To initialize newly created github repo add new remote. Let's name it other-repo.
git remote add other-repo https://github.com/xxx/yyy.git
To push local-branch as remote master:
git push -u other-repo local-branch:master
To later push any new commits (this can be simplified using git's config option push.default):
git push other-repo local-branch:master
To delete the tracking without deleting remote branch:
git branch local-branch --unset-upstream
To make existing local branch track existing remote branch (master):
git branch other-repo/master local-branch
To see all the trackings:
git branch -vv

git version 1.9.1