2013-05-02 38 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(); 
    }