Announcement Announcement Module
Collapse
No announcement yet.
Circular dependencies using Spring 3 java config, simple example Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Circular dependencies using Spring 3 java config, simple example

    Hi all! new to Spring and new to forum. Here is what I have done today resolving the circular dependency in Spring 3.0 Java config style. Please share if neone having better solution:
    -------------
    package com.sudip;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationC onfigApplicationContext;
    import org.springframework.context.support.ClassPathXmlAp plicationContext;

    public class Dependent {
    private Collaborator collaborator;
    private int i;
    public Dependent(int i) {
    this.i = i;
    }
    public int getI() {
    return i;
    }
    public void setCollaborator(Collaborator collaborator) {
    this.collaborator = collaborator;
    }
    public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.cl ass);
    Dependent dp = ctx.getBean(Dependent.class);
    dp.collaborator.printTask("Hi collaborator!");

    }

    }
    --------------
    package com.sudip;

    public class Collaborator {

    private String str;
    private Dependent d;
    public Collaborator(String str, Dependent d) {
    this.str = str;
    this.d = d;
    }
    public void printTask(String string) {
    System.out.println(string + " / " + str + d.getI());

    }


    }
    -------------
    package com.sudip;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configurati on;

    @Configuration
    public class SpringConfig {

    private Dependent dp; // we had to take reference of dependent object as instance variable

    @Bean
    public Dependent dependent() {
    dp = new Dependent(1111);
    dp.setCollaborator(collaborator());
    return dp;
    }

    @Bean
    public Collaborator collaborator() {
    return new Collaborator("XXXX", dp);
    }
    }

    Thanks...
Working...
X