-
Aug 29th, 2011, 03:34 AM
#1
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...
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules