@PropertySource:加载指定路径下的配置文件
全局配置文件的属性值注入到实体类的实现方式利用了@ConfigurationProperties(prefix = "?")和@Component两个注解,
代码如下:
Person.java
@Component
@ConfigurationProperties(prefix = "person")
public class Person{
private String name;
private Integer age;
//getter and setter
//Override toString()
}
application.yml
person:
name: 张三
age: 20
注 : @Component注解为将当前类作为Spring容器的组件
@ConfigurationProperties注解之所以可以直接读取到这个“person”前缀是因为默认情况下类读取全局配置文件application.properties和application.yml,但是全局配置文件毕竟只有一个,而一个项目工程可以有很多配置属性,如果全部放在全局配置文件里,那这个配置文件的内容将非常冗杂,不易管理与维护,所以当组件类想读取自定义配置文件的时候,就可以用@PropertySource注解读取指定配置文件,从字面意义上理解这个注解内容为“属性资源”也就是自定义属性文件资源,代码示例如下:
Person.java
@Component
@PropertySource(value = {"classpath:person.yml"})
@ConfigurationProperties(prefix = "person")
public class Person{
private String name;
private Integer age;
//getter and setter
//Override toString()
}
person.yml
person:
name: 李四
age: 20
@ImportResource:将指定配置文件作为组件导入Spring容器中
SpringBoot应用不能把一个随意创建的XML文件定义的beans注入到Spring容器中,需要@ImportResource注解定义到启动类上实现注入;代码如下:
自定义Service:HelloService.java
public class HelloService{}
自定义xml:beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "helloService" class="com.ls.annotation.service.HelloService"></bean>
</beans>
注:此时Spring容器并不能识别这个beans.xml,当然也不能从全局对象ApplicationContext中获取到这个id为"helloService"的bean
测试代码:
@SpringBootTest
public class SpringBootTest{
@Autowired
ApplicationContext ioc;
@Test
public void getBeans(){
boolean b = ioc.containsBean("helloService");
System.out.println(b);
//输出为false
}
}
怎么把一个自定义xml里定义的bean注入到Spring容器中?@ImportResource实现
在SpringBoot启动类上标注如下:
@ImportResource(value = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBootApplication{
public static void main(String [] args){
SpringApplication.run(SpringBootApplication.class,args);
}
}
标注后再运行一遍测试类,打印true,说明Spring容器已经加载到了beans.xml的id为helloService的bean。
@Bean:可以达到和@ImportResource同样的效果,只是@Bean实现的方式是注解代码代替xml配置文件
同样,把一个Service注入到SpringBoot应用中的Spring容器里用@Bean的实现如下:
com.config.MyConfig.java
@Configuration
public class MyConfig{
@Bean
public HelloService getHelloService(){
return new HelloService();
}
}
测试代码:
@SpringBootTest
public class SpringBootTest{
@Autowired
ApplicationContext ioc;
@Test
public void getBeans(){
boolean b = ioc.containsBean("getHelloService");
System.out.println(b);
//输出为true
}
}