首页 > 其他 > 详细

@PropertySource 和 @ImportResource和配置问价占位符02

时间:2020-05-12 19:17:00      阅读:64      评论:0      收藏:0      [点我收藏+]

@PropertySource 和 @ImportResource

@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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!