I am having two main issues with Spring bean configuration: 1. The properties I read through a properties file are not persisting when I retrieve the bean from my application context. 2. I'm having trouble figuring out how to set the value of a bean as another bean- in my below example, I'm trying to set the Plan bean's Metric property to be a certain bean.
I have two small classes, a Metric, and a larger Plan:
@Component
public class Metric {
@Value("${nameOfMetric}")
String name;
@Value("${empID}")
String empID;
@Value("${value:0.0}")
Double value;
}
And a larger Plan object which has three different Metrics as properties:
public class Plan {
public Metric hoursWorked;
public Metric monthlyDeals;
public Metric monthlyGoal;
...}
I also have a properties file that I am reading from:
nameOfMetric = Untitled Metric
empID = Unknown
hoursWorked = 120.0
monthlyDeals = 40.0
monthlyGoal = 100.0
Is there a way for me to create beans for each of the metrics (hoursWorked, monthlyDeals, monthlyGoal), and then inject each of these beans into a Plan bean? So far, I have tried to using a PropertyConfig class with the @Configuration annotation:
@Inject
private Environment environment;
private Metric injectMetric(String propertyName){
Metric metric = new Metric();
metric.setEmpID(environment.getProperty("empID"));
metric.setName(propertyName);
metric.setValue(Double.parseDouble(environment.getProperty(propertyName)));
System.out.println("Metric injected: " + metric.toString());
return metric;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean(name = {"hoursWorkedBean"})
@Scope("prototype")
public Metric hoursWorked() {
Metric metric = injectMetric("hoursWorked");
return metric;
}
But when I try to access this bean, I get the default or null values in my main application, signalling that these properties have not persisted:
Metric hoursWorked = (Metric) ctx.getBean("hoursWorkedBean");
System.out.println(hoursWorked.getName()); // prints out "Untitled Metric", but should print out "hoursWorked"