Java 获取@Service注释类的bean?

Java 获取@Service注释类的bean?,java,spring,web-applications,spring-mvc,spring-annotations,Java,Spring,Web Applications,Spring Mvc,Spring Annotations,在我的web应用程序中,我没有使用applicationContext.xml。如何获得@Service注释类的bean 如果我在我的web应用程序中使用了applicationContext.xml,我必须每次加载applicationContext.xml,以获取@Service注释类的bean 我用这种方式 WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getS

在我的web应用程序中,我没有使用
applicationContext.xml
。如何获得
@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
bean的正确方法是什么?

既然您正在使用注释,我相信您更喜欢使用@Autowired。如果您有一个类将调用
ServerConnection
(比如在package
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" />


希望我能回答您的问题。

如果您使用基于注释的配置,您可以使用
@Autowired
按类型获取bean,或者使用
@Resource
按名称获取bean。对于任何特定属性,仅使用其中一个(以避免混淆)


,但我不喜欢这样,因为随着豆子数量的增加,它变得越来越不好。YMMV.

如果您在spring之外的一些bean中工作,那么您可以使用普通的spring注释:

@Autowired
private Dependency1 dependency1;

@Autowired
private Dependency2 dependency2;

@Autowired
private Dependency2 dependency2;
然后在此类内部调用一次:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

注入所有依赖项。如果您有多个依赖项,可能会更方便。

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

此上下文可用于获取由注释
@Bean
@Service
创建的Bean 作为


context.getBean(className.class)

我已经用过了。我的问题是如何从这种方式中分离出这个类的实例。除此之外,还有你上面提到的,我相信没有其他方式,也就是说,如果你想利用Spring的DI.hi Maaksym,我尝试使用SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);但它确实注入了applicationContext.xml文件中描述的bean,而不是注释的bean。@Amit Sharma请将您的问题作为单独的问题发布
@Autowired
private Dependency1 dependency1;

@Autowired
private Dependency2 dependency2;

@Autowired
private Dependency2 dependency2;
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);