在Java Spring中将一个bean的值设置为另一个bean

时间:2017-04-12 07:59:45

标签: java spring spring-mvc

我遇到Spring bean配置的两个主要问题: 1.当我从应用程序上下文中检索bean时,通过属性文件读取的属性不会持久存在。 2.我无法弄清楚如何将bean的值设置为另一个bean - 在我的下面的例子中,我试图将Plan bean的Metric属性设置为某个bean

我有两个小班,一个指标和一个更大的计划:

return sb.toString();

一个较大的Plan对象,它有三个不同的Metrics作为属性:

@Component
public class Metric {

   @Value("${nameOfMetric}")
   String name;

   @Value("${empID}")
   String empID;

   @Value("${value:0.0}")
   Double value;
   }

我还有一个我正在阅读的属性文件:

public class Plan {

public Metric hoursWorked;

public Metric monthlyDeals;

public Metric monthlyGoal;
...}

我有没有办法为每个指标(hoursWorked,monthlyDeals,monthlyGoal)创建bean,然后将每个bean注入Plan bean?到目前为止,我已经尝试将PropertyConfig类与@Configuration注释一起使用:

nameOfMetric = Untitled Metric
empID = Unknown
hoursWorked = 120.0
monthlyDeals = 40.0
monthlyGoal = 100.0

但是当我尝试访问这个bean时,我在主应用程序中获取了默认值或空值,表明这些属性没有持久存在:

@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;
}

2 个答案:

答案 0 :(得分:1)

你需要自动装配你的metrices

public class Plan {

@Autowired   
public Metric hoursWorked;

@Autowired
public Metric monthlyDeals;

@Autowired
public Metric monthlyGoal;
...}

答案 1 :(得分:0)

您可以在Spring Boot应用程序中使用@ConfigurationProperties。

您可以在Spring Boot应用程序中进行以下配置:

<强>资源/ application.yml

metrics:
  hoursWorked:
    name: one
    empID: 1
    value: 1.23
  monthlyDeals:
    name: two
    empID: 2
    value: 2.34
  monthlyGoal:
    name: three
    empID: 3
    value: 3.45

Metric.java (不要忘记getter / setter)

public class Metric {
    private String name;
    private String empID;
    private Double value;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmpID() {
        return empID;
    }

    public void setEmpID(String empID) {
        this.empID = empID;
    }

    public Double getValue() {
        return value;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Metric{" +
                "name='" + name + '\'' +
                ", empID='" + empID + '\'' +
                ", value=" + value +
                '}';
    }
}

Metrics.java (定义指标名称/限定符/配置)

public class Metrics {

    public static final String HOURS_WORKED = "hoursWorked";
    public static final String MONTHLY_DEALS = "monthlyDeals";
    public static final String MONTHLY_GOAL = "monthlyGoal";
}

MetricsConfiguration.java (创建bean并从配置初始化它们)

@Configuration
public class MetricsConfiguration {

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    @Qualifier(Metrics.HOURS_WORKED)
    @ConfigurationProperties(prefix = "metrics." + Metrics.HOURS_WORKED)
    public Metric hoursWorked() {
        return new Metric();
    }

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    @Qualifier(Metrics.MONTHLY_DEALS)
    @ConfigurationProperties("metrics." + Metrics.MONTHLY_DEALS)
    public Metric monthlyDeals() {
        return new Metric();
    }

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    @Qualifier(Metrics.MONTHLY_GOAL)
    @ConfigurationProperties("metrics." + Metrics.MONTHLY_GOAL)
    public Metric monthlyGoal() {
        return new Metric();
    }
}

DemoRunner.java (用于测试代码的命令行运行器)

@Component
public class DemoRunner implements CommandLineRunner
{
    @Autowired
    private List<Metric> allMetrics;

    @Autowired
    @Qualifier(Metrics.HOURS_WORKED)
    private Metric hoursWorkedMetric;

    @Autowired
    @Qualifier(Metrics.MONTHLY_DEALS)
    private Metric monthlyDealsMetric;

    @Autowired
    @Qualifier(Metrics.MONTHLY_GOAL)
    private Metric monthlyGoalMetric;

    @Override
    public void run(String... args) throws Exception {
        System.out.println();

        System.out.println("All metrics:");
        allMetrics.stream().forEach(System.out::println);

        System.out.println();
        System.out.println("HOURS_WORKED metric: " + hoursWorkedMetric);
        System.out.println("MONTHLY_DEALS metric: " + monthlyDealsMetric);
        System.out.println("MONTHLY_GOAL metric: " + monthlyGoalMetric);

        System.out.println();
    }
}

DemoApplication.java (SpringBoot应用程序初始化)

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}