@PropertySource
将指定类路径下的.properties一些配置加载到Spring当中,
有个跟这个差不多的注解@PropertySources
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PropertySources {PropertySource[] value();}
使用方式,在@Configuration上面加上这个即可,不仅可以加载properties文件,加载Spring的xml也是可以的
@PropertySource(value = "classpath:/test04.properties")
这个是注解的方式,如果还是xml怎么办,利用context包下标签即可加入
<context:property-placeholder location="classpath:***.properties"/>
那这个注解是如何加载的呢,专门有个BeanFactoryPostProcessor解析这个注解,PropertySourcesPlaceholderConfigurer,可以自行去看一下源代码,这里就不介绍了
组件赋值
@Value:1、直接赋值,2、支持SpringEL表达式,3、读取环境变量数据
//直接赋值@Value("i am bird")private String name;//通过计算赋值@Value("#{24-6}")private Integer age;//通过获取Environment变量赋值@Value("${bird.name}")private String propertiesName;
SpringEL表达式不仅仅是上面这些,还有许多没有写出来,大家可以参考官网docs比较好,避免误导各位,请单击SpringEL。
@Autowired:Spring默认取值器(默认按class取值),可作用于set方法上
如果容器中有多个同类型的bean,则按同变量名称BEAN名称,没有找到抛异常,可和@Qualifier一同使用,如果容器没有同类的BEAN,则默认报错,可调整required值,当required=false则没有取值为null,优先获取@Component注入的BEAN
@Resource:javax.annotation包下(默认按变量名称取值) 也是JSR250的规范中的,可作用于set方法上, name:按BEAN名称取值,type:按类型取值,不支持@Primary
@Qualifier:指定从Spring容器获取指定bean名称,和@Autowired一起使用
@Primary:当Spring有多个同类型bean时,选中其中一个为默认首选
@Inject:javax.inject包下,属于JSR330规范中的,需额外引包
<dependency><groupId>javax.inject</groupId><artifactId>javax.inject</artifactId><version>1</version></dependency>
这次就简单的介绍一下就好了,什么在哪里加载赋值的呀,就不细说了,都是基于BeanPostProcessor实现的,可自行调试代码查看