2011-08-30 225 views
4

對於新的遺留應用程序,我必須使用最新的Spring框架3.x與Hibernate 3.x.之前我用xml配置使用Spring IoC。現在我想去基於註釋的IoC。spring 3註解依賴注入

玫瑰印度下面的鏈接顯示使用註釋沒有XML文件。 rose india

但我發現在另一個網站上實施的一些其他的方式: blog

我很困惑在這裏與最新的技術來實現的IoC哪種方式。 請參考一些好的網站進行舉例。也請分享一些示例代碼IoC與註釋。

編輯:

Spring參考文獻3.x的說使用@Configuration或XML配置即具有註釋<上下文:註解的配置/>。哪一個更好用?爲什麼?

+4

忽略玫瑰印度的東西。這絕對是可怕的。 – skaffman

+0

我在這裏維護一個操作示例:http://tshikatshikaaa.blogspot.nl/2012/08/spring-ioc-container-with-annotations.html – JVerstry

回答

2

你最好打賭是從Spring 3.0 Documentation開始。如果您已經熟悉使用xml配置的依賴注入,請查看Section 3.9 Annotation-based container configuration中Spring的註釋支持。應該有足夠的細節來幫助你開始。

如果這不是一個WebApp,並且您需要自己加載ApplicationContext,則應該查看Section 3.11 Java-based container configuration。本節詳細介紹如何使用xml配置創建ApplicationContext

我會建議使用@Autowired註解接線與@Component標註爲ApplicationContext中定義豆,並使用由AnnotationConfigApplicationContext提供的scan(String)方法來查找所有註釋組件:

public static void main(String[] args) { 
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
    ctx.scan("your.package.here"); 
    ctx.refresh(); 
    MyService myService = ctx.getBean(MyService.class); 
    //use myService 
} 
+0

我需要使用新的AnnotationConfigApplicationContext();加載xml文件?在XML文件中只有bean聲明是足夠的? – TechFind

+0

我已經更新了我的答案和其他一些信息。 –

+0

好的,在我的上下文xml文件中是否需要爲IoC指定bean id和它的屬性? – TechFind

1

我建議用添加去:<context:annotation-config />添加到您的xml上下文文件以使其加載註釋。然後使用:<context:component-scan base-package="my.package" />導入所有註釋的類。這不需要任何代碼,而且非常乾淨。您還可以將包含/排除過濾器添加到xml文件中的掃描中。

然後,只需在課程中使用任何註釋。確保註解構造爲他們提供稍後參考的ID,即@Component(「mycomponentbean」)。