Reputation: 1601
I have some class:
public class MyResources {
@Value("${my.value}") // value always is null!!!
private String PATH_TO_FONTS_FOLDER;
}
and I have a property file:
my.value=/tmp/path
and my config class:
@Configuration
public class MyBeanConfig {
@Bean
public MyResources myResources() throws Exception
{
return new MyResources();
}
}
How can I inject property from my property file into this class field?
Upvotes: 0
Views: 563
Reputation: 3370
You have to mark MyResources
with the @Component
annotation, for Spring to be able to manage that bean.
This will do the job:
@Component
public class MyResources {
@Value("${my.value}") // value always is null!!!
private String PATH_TO_FONTS_FOLDER;
}
Upvotes: 3
Reputation: 2756
One approach would be to move @Value("${my.value}")
to MyBeanConfig
, and add a constructor to MyResources
which accepts the value. For example:
@Configuration
public class MyBeanConfig {
@Value("${my.value}")
private String PATH_TO_FONTS_FOLDER;
@Bean
public MyResources myResources() throws Exception {
return new MyResources(PATH_TO_FONTS_FOLDER);
}
}
But based on the example, there's no need for MyBeanConfig
. Simply mark MyResources
as @Component (or other as appropriate) to allow Spring to manage the creation of the instance. If Spring creates the instance (instead of using new
from the example), then the @Value will be injected.
Upvotes: 1