2013-05-02 73 views
3

考虑下面的@Autowired资源:使用与“尝试用资源”

public class ResourceOne implements AutoCloseable {...} 

ResourceOne中(春)XML配置实例化一个实例。

由于您需要在try块中实例化资源,该对象(何时自动装配)应该如何与“try-with-resources Statement”一起使用?

一种方法可以是使用参考(见下文),但这并不是最佳选择。

public class Test { 
@Autowired 
ResourceOne test; 
//... 
public void execute() 
{ 
//... 
try (ResourceOne localTest = test) 
{ 
    localTest.init() 
    localTest.readLine(); 
    //... 
} 
} 
+0

你试着用''(ResourceOne localTest = test)''来实现什么' – 2013-05-02 15:57:27

+0

这是一个自动关闭'test'的解决方法。 – user2343593 2013-05-03 08:43:45

回答

1

AFAIK我认为你采取的方法似乎是唯一的方法。

try (ResourceOne localTest = test) 
{ 
    localTest.init() 
    localTest.readLine(); 
    //... 
} 

我假设你有自动装配的资源声明与原型范围,虽然正确。

@Bean 
    @Scope(value="prototype", proxyMode=ScopedProxyMode.DEFAULT) 
    public Resource1 resource1() { 
     return new Resource1(); 
    }