@PropertySource:加载指定的配置文件,写在一个实体类上

@ConfigurationProperties : 默认加载全局的配置文件
@ImportResources:导入Spring的配置文件,让配置文件里面的内容生效
在resources目录下创建一个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.nylg.service.HelloService"></bean>
</beans>
测试
@SpringBootTest
@RunWith(SpringRunner.class)
class SpringBootConfigApplicationTests {
@Autowired
Person person;
@Autowired
ApplicationContext applicationContext;
@Test
public void testHelloService(){
Object o= applicationContext.getBean("helloService");
System.out.println(o);
}
@Test
void contextLoads() {
System.out.println(person);
}
}
打印没被定义
SpringBoot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别,想让SpringBoot配置文件生效,加载进来,@ImportResource标注在主配置类上,在参数locations中写上配置文件路径即可
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBootConfigApplication {
运行测试文件,打印出o的地址
进化
SpringBoot推荐给容器中添加组件的方式:推荐使用全注解的方式
1.配置类=====Spring配置文件 @Configuration
2.使用Bean给容器中添加组件
/**
* @Configuation:指明当前类是一个配置类,就是用来代替之前的Spring配置文件
* 在配置文件中用<bean></bean>标签添加组件
*/
@Configuration
public class MyAppConfig {
//将方法的返回值添加到容器中,容器中的这个组件默认的id就是方法名
@Bean
public HelloService helloService(){
System.out.println("配置类@Bean给容器添加组件了");
return new HelloService();
}
}
测试:
@SpringBootTest
@RunWith(SpringRunner.class)
class SpringBootConfigApplicationTests {
@Autowired
Person person;
@Autowired
ApplicationContext applicationContext;
@Test
public void testHelloService(){
Object o= applicationContext.getBean("helloService");
System.out.println(o);
}
@Test
void contextLoads() {
System.out.println(person);
}
}
1.RandomValuePropertySource:配置文件中可以使用随机数
${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}
2.属性配置占位符,占位符获取之前配置的值,如果没有可以用:指定默认值
-- 可以在配置文件中引用前面配置过的属性(优先级前面配置过的这里都能使用)
--${app.name:默认值} 来指定找不到属性时的默认值
person.name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.list=a,b,c
#person.dog.name=${person.name}_dog
#获取值person.hell 取不出来值默认为hello
person.dog.name=${person.hello:hello}_dog
person.dog.age=15
@PropertySource 和 @ImportResource和配置问价占位符02
原文:https://www.cnblogs.com/ghwq/p/12877909.html