如何使用Spring手动创建类实例

时间:2017-01-16 02:46:45

标签: java spring dependency-injection

我正在使用Spring Framework for Dependency Injection。有一次,我将某个类的实例注入另一个类,我需要创建一个同一个类的附加临时对象。我可能可以将注入的bean的范围更改为原型但我想知道是否还有另一种简单的方法可以做到这一点?

我唯一的想法是使用new创建它,但想知道是否有适当的方法来使用Spring。

只是一个一般的例子:

@Inject
private ClassA classA;

public void methodA() {

// here I need another instance of ClassA to be used in the scope of this method

}

2 个答案:

答案 0 :(得分:2)

只需将其子类化并使用prototype范围。

@Component
@Scope("prototype")
public class ClassB extends ClassA {
}

然后,使用它:

@Autowired
private ApplicationContext context;

public void methodA(){
  // will return a new instance (still a bean) every time its called
  ClassB bean = context.getBean(ClassB.class); 
  ...
}

如果您愿意,也可以转换为ClassA并使用bean名称。

答案 1 :(得分:-5)

根据另一个ClassA实例的目的,有两种方法可以做到这一点。 第一, 您可以使用“new”关键字创建新对象。

public void methodA()
{
 ClassA antherClassAInstance = new ClassA();   
}

当您只想为此方法使用新实例时,此approch非常合适。

其次, 使用@Autowired注释声明全局实例。

@Autowired
ClassA antherClassAInstance;