Reference another bean and set property : XML Bean « Spring « Java

Reference another bean and set property

File: context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="encyclopedia" class="HardcodedEncyclopedia"/>

    <bean id="oracle" class="BookwormOracle">
        <property name="encyclopedia" ref="encyclopedia"/>



import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.xml.XmlBeanFactory;

public class Main {
  public static void main(String[] a) {
    XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml"));

    Oracle oracle = (Oracle) bf.getBean("oracle");
    System.out.println("Meaning of life is " + oracle.defineMeaningOfLife());

interface Oracle {

  String defineMeaningOfLife();

interface Encyclopedia {

  Long findLong(String entry);
class BookwormOracle implements Oracle {
  private Encyclopedia encyclopedia;

  public String defineMeaningOfLife() {
      Long ageOfUniverse = this.encyclopedia.findLong("AgeOfUniverse");
      Long constantOfLife = this.encyclopedia.findLong("ConstantOfLife");
      return String.valueOf(ageOfUniverse / constantOfLife);

  public void setEncyclopedia(Encyclopedia encyclopedia) {
      this.encyclopedia = encyclopedia;

class HardcodedEncyclopedia implements Encyclopedia {
  private Map<String, Long> entryValues = new HashMap<String, Long>();

  public HardcodedEncyclopedia() {
      this.entryValues.put("AgeOfUniverse", 13700000000L);
      this.entryValues.put("ConstantOfLife", 326190476L);

  public Long findLong(String entry) {
      return this.entryValues.get(entry);

       2,600 k)

Related examples in the same category

1.XML Bean Injection
2.Static Factory
3.Serach By Base Package
4.throw RequiredPropertyNotSetException
5.Properties File Based Spring Bean
6.Non Static Factory
7.Local Reference
8.Link With DataSource
9.Inheritance Demo
10.HierarchicalBeanFactory Demo
11.Filtered By Annotation
12.destroy method
13.dependency check Demo
14.Custom InitializationMethod
15.component scan
16.Component Scan and scope
17.Component Filter Assignable
18.implements BeanNameAware
19.Bean Lifecycle Initializing
20.Bean Lifecycle DisposableBean
22.Alias Bean Demo