2013-04-11 94 views
2

在我的web應用程序中,我沒有使用applicationContext.xml。我怎樣才能得到@Service註釋類的bean?獲取@Service註釋類的bean?

如果我在我的Web應用程序中使用applicationContext.xml,我必須每次加載applicationContext.xml以獲得@Service帶註釋的類的bean。

我用這樣的方式

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext); 
ServerConnection con = (ServerConnection) ctx.getBean("con"); 

我的服務類將是作爲,

@Service or @Service("con") 
public class ServerConnection { 

    private TServerProtocol tServerProtocol; 
    private URI uri; 

    public TServerProtocol getServerConnection(){ 

     System.out.println("host :"+host+"\nport :"+port); 

     try { 
      uri = new URI("tcp://" + host + ":" + port); 
     } catch (URISyntaxException e) { 
      System.out.println("Exception in xreating URI Path"); 
     } 

     tServerProtocol = new TServerProtocol(new Endpoint(uri)); 
     return tServerProtocol; 
    } 
} 

任何其他方式獲得一個bean這個類的

什麼是適當的方式在Spring3.x核心應用程序和Web應用程序的情況下獲得@Service註解類的豆?

回答

1

如果您正在使用基於註釋的配置,則使用@Autowired來獲取按其類型的bean或@Resource以通過其名稱獲取bean。對於任何特定的財產,只能使用其中的一種(以防止混淆)。

@Autowired 
private ServerConnection connection; 
@Resource(name = "con") 
private ServerConnection connection; 

There's also @Inject,但我不喜歡這樣,因爲它得到豆子的數量上升較少不錯。因人而異。

0

由於您正在使用註釋,我相信您更喜歡使用@Autowired。如果你有一個類,將調用ServerConnection(可以說CallingClass下包com.foo),那麼這就是它會是什麼樣子:

package com.foo; 

@Component 
public class CallingClass{ 

    @Autowired 
    private ServerConnection serverConnection 

    // add your getters and setters 
} 

然後在你的applicationContext.xml只需添加以下

<context:component-scan base-package="com.foo" /> 

希望我回答你的問題。

+0

我用這個了。我的問題是如何從這種方式獲得這個類的實例。 – 2013-04-11 10:38:05

+0

除了這個以及你上面提到的,我相信沒有別的辦法,那就是如果你想利用Spring的DI。 – cRx 2013-04-11 10:53:26

0

如果你在一些豆外彈簧工作,那麼你可以正常使用Spring註解:

@Autowired 
private Dependency1 dependency1; 

@Autowired 
private Dependency2 dependency2; 

@Autowired 
private Dependency2 dependency2; 

然後從這個類裏面調用一次:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 

注入所有的依賴關係。如果你有多個依賴關係可能會更方便。

+0

嗨Maaksym,我試過使用SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);但它確實注入了applicationContext.xml文件中描述的bean,而不是註釋的bean。 – 2013-10-08 12:32:36

+0

@Amit Sharma請將您的問題作爲單獨問題發佈 – 2013-10-08 15:25:00

5

ApplicationContext context=SpringApplication.run(YourProjectApplication.class, args);

此範圍內可用於獲取的註釋@Bean@Service 創建豆類

context.getBean(className.class);