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 在@Component中使用@PropertySouce_Spring - Fatal编程技术网

Spring 在@Component中使用@PropertySouce

Spring 在@Component中使用@PropertySouce,spring,Spring,我试图在@组件中使用@PropertySource,例如: @Component @PropertySource("somepropertiesfile.properties") public class Student { ... } 它工作得很好 我想了解,将@PropertySource与@Component一起使用和将@PropertySource与@Configuration一起使用有什么不同 将@PropertySource与@Component配置一起使用是否有任何区别或

我试图在
@组件中使用
@PropertySource
,例如:

@Component
@PropertySource("somepropertiesfile.properties")
public class Student {
    ...
}
它工作得很好

我想了解,将
@PropertySource
@Component
一起使用和将
@PropertySource
@Configuration
一起使用有什么不同


@PropertySource
@Component
配置一起使用是否有任何区别或影响
本身就是
组件
类型,请查看下面的@Configuration注释实现

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {

}
来自API

组件:表示带注释的类是“组件”。当使用基于注释的配置和类路径扫描时,此类类被视为自动检测的候选类

配置:表示一个类声明了一个或多个@Bean方法,并且可以由Spring容器处理,以便在运行时为这些Bean生成Bean定义和服务请求

@Bean注释用于指示一个方法实例化、配置和初始化一个要由SpringIOC容器管理的新对象。这些与Spring的XML配置相同
您可以对任何Spring@组件使用@Bean注释的方法,但是,它们最常用于@configurationbean

在这里,您还可以在@Component类中使用@PropertySource,但这些最适合@Configuration类,因为它是一项与配置相关的任务


您可以参考详细信息。

我在文档中读到“您可以对任何Spring组件使用带Bean注释的方法,但是,它们最常用于配置Bean。”。但在任何地方都没有提到我们可以将PropertySource与@Component一起使用,或者notPropertySource是配置任务的一种类型,更好的地方是@configuration类。例如,我们也可以在组件类中定义
@Bean
带注释的方法,但我们更喜欢配置类,因为它是单独的注释名称。我同意文档没有指定这个案例,但我们可以将这个案例与@Bean定义案例关联起来。不确定spring以后是否会限制在@Configuration类中指定所有配置,所以最好遵循最合适的路径。