2012-04-30 56 views
2

部分非托管类我在我的代码创建MyClass类的众多对象。天色管理,在Java春天

public class MyClass { 

    private String a; 
    private Integer b; 
    private SomeObject c; 

    public A(String a, Integer b, SomeObject c) { 
     this.a = a; this.b = b; this.c = c; 
    } 

} 

反正我有可以使用Spring只是SomeObject注入到这个类,当我创建的MyClass的对象。 MyClass的是春季管理,因为我需要以随机方式产生在我的代码相同的对象。我如何解决这个问题。

  1. 我做的getBean在我的SomeObject主要方法,并把它传递到MyClass的,每当我创造它的对象。

  2. 我创建了一个SomeObjectSingleton这是了ApplicationContextAware(它本身做了的getBean得到SomeObject)。我直接在MyClass构造函数中调用SomeObjectSingleton.getImpl。

你认为哪种方式最合适,还是有其他更好的方法来解决这个问题。

回答

2

Spring管理解决方案

如果没有与制作MyClass Spring管理,然后you could set the singleton property to false问题。这样一来,只要你拨打context.getBean()MyClass一个新的实例将被实例化。

然后在上下文XML文件,你可以连线SomeObjectMyClass并保留其他两个属性(String aInteger b)未设置。需要注意的是,您必须使用setter注入,而不是构造注入,至少对于未在您的上下文XML文件中设置的属性。

非Spring管理的解决方案

如果由于某种原因,你需要MyClass不被Spring管理,那么我建议你的第一个方法,因为它使用了比你的第二个方法SomeObjectMyClass之间的弱耦合。过度使用单例会导致代码混淆,因为它们本质上是一种隐藏依赖关系的全局变量。请参阅here以获得更详细的论点。