簡體   English   中英

獲取@Service注釋類的bean?

[英]Get bean of @Service annotated class?

在我的Web應用程序中,我沒有使用applicationContext.xml 如何獲取@Service注釋類的bean?

如果我在我的Web應用applicationContext.xml中使用了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注釋類的bean的正確方法是什么?

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

此上下文可用於獲取注釋@Bean@Service創建的bean

context.getBean(className.class);

如果使用基於注釋的配置,則使用@Autowired按類型獲取bean,或使用@Resource以獲取bean的名稱。 對於任何特定屬性,只使用其中一個(以避免混淆)。

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

還有@Inject ,但我不喜歡它,因為隨着bean數量的增加,它變得不那么好了。 因人而異。

由於您正在使用注釋,我相信您更願意使用@Autowired 如果你有一個將調用ServerConnection的類(比如com.foo包下的CallingClass ),那么它就是這樣的:

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" />

希望我回答你的問題。

如果您在spring之外的某個bean中工作,那么您可以使用普通的Spring注釋:

@Autowired
private Dependency1 dependency1;

@Autowired
private Dependency2 dependency2;

@Autowired
private Dependency2 dependency2;

然后從這個類的內部調用一次:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

注入所有依賴項。 如果您有多個依賴項,可能會更方便。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM