Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否只向Spring应用程序上下文注册接口的实现?_Spring - Fatal编程技术网

是否只向Spring应用程序上下文注册接口的实现?

是否只向Spring应用程序上下文注册接口的实现?,spring,Spring,我有一套课程如下 public class ServiceA implements CommonInterface { public void startA() { .... } } public class ServiceB implements CommonInterface { public void startB() { .... } } 在Spring框架中,有没有办法只自动注册实现应用程序上下文公共接口的类并访问它们

我有一套课程如下

public class ServiceA implements CommonInterface
{
   public void startA()
   {
       ....
   }
}

public class ServiceB implements CommonInterface
{
   public void startB()
   {
       ....
   }
}

在Spring框架中,有没有办法只自动注册实现应用程序上下文公共接口的类并访问它们?

是的,这是可能的。如果您使用的是Java配置,则可以使用@componescan将组件筛选为实现特定接口的组件。您需要禁用Spring使用的默认过滤器(基于检测原型注释类,即@Component、@Service等)


使用上下文在xml中也可以实现同样的效果:组件扫描是的,这是可能的。如果您使用的是Java配置,则可以使用@componescan将组件筛选为实现特定接口的组件。您需要禁用Spring使用的默认过滤器(基于检测原型注释类,即@Component、@Service等)


在xml中使用上下文也可以实现这一点:组件扫描

为什么不对任何实现使用
@Service
注释?为什么不将
@Autowire
与实现的类型一起使用来访问呢?@KenBekov:
@Service
将通过扫描基本包来启用注册。但我需要更多的过滤器,比如实现CommonInterface的类类型。
@Autowire
另一方面,只会帮助自动注入引用的对象,这不是我的方案。为什么不对任何实现使用
@Service
注释?为什么不将
@Autowire
与实现的类型一起使用来访问呢?@KenBekov:
@Service
将通过扫描基本包来启用注册。但我需要更多的过滤器,比如实现CommonInterface的类类型。
@Autowire
另一方面,只会帮助自动注入引用的对象,这不是我的设想,是的。看起来不错。不过,我没有@Configuration类来注册服务。同样的过滤器也适用于applicationcontext的扫描api。让我查一查。对不起,我要换个说法。我没有beans.xml文件,也没有
@configuration
类。我只想实例化一个
annotationConfigApplicationContext
对象,并使用它的
scan
api提供过滤器。
scan
的功能类似于
componentscan
,但它是通过
applicationcontext
对象实现的,而不是
config
对象。这没问题。我不介意创建一个配置类。但是
value=CommonInterface
正在抛出一个编译器错误-标记“=”上的语法错误。浏览过,但无法理解。太好了。谢谢。看起来不错。不过,我没有@Configuration类来注册服务。同样的过滤器也适用于applicationcontext的扫描api。让我查一查。对不起,我要换个说法。我没有beans.xml文件,也没有
@configuration
类。我只想实例化一个
annotationConfigApplicationContext
对象,并使用它的
scan
api提供过滤器。
scan
的功能类似于
componentscan
,但它是通过
applicationcontext
对象实现的,而不是
config
对象。这没问题。我不介意创建一个配置类。但是
value=CommonInterface
正在抛出一个编译器错误-标记“=”上的语法错误。浏览过,但无法理解。太好了。谢谢
@Configuration
@ComponentScan(basePackages = {"com.mydomain.myapp.service"} , useDefaultFilters = false , includeFilters = {@Filter(type = FilterType.ASSIGNABLE_TYPE , value = CommonInterface.class)})
public class AppConfig{
   //@Bean methods
}