spring学习笔记(七)springboot 配置

2.6 @propertySource,@ImportSource,@Bean介绍

1. @propertySource

加载指定的配置文件:person.proerties

person.age=19
person.birth=2019/12/12
person.boss=false
person.dog.name=dog
person.dog.age=2
person.last-name=里斯
person.maps.v1=kd
person.maps.v2=34

Person类:

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 *
 * @ConfigurationProperties:告诉springBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *    (prefix = " person "):配置文件中哪个下面的所有属性进行一一映射,默认是从全局配置文件中获取
 *    只有这个组件时容器中的组件,才能提供@ConfigurationProperties功能
 * @PropertySource:加载指定的配置文件,可以配置多个文件(支持yml及peoperties两种方式)
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String, Object> maps;
    private List<Object> list;
    private Dog dog;
}

测试:
在这里插入图片描述

2.@ImportSource

导入Spring配置文件,使配置文件中的内容生效,比以前使用spring配置文件使用简单

以前的方式

1.存在HelloService类
2.编写Spring配置文件: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.atguigu.springboot.service.HelloService"/>
</beans>

2.使用@ImportSource标注到主配置类中

//导入Spring的配置文件让其生效
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class Springboot01HelloworldQuickApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot01HelloworldQuickApplication.class, args);
    }

3.测试是否成功

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot01HelloworldQuickApplicationTests {

    @Autowired
    ApplicationContext ioc;
    @Test
    public void testHelloService(){
        boolean b = ioc.containsBean("helloService");
        System.out.println("helloService result :"+b);
    }

在这里插入图片描述

3.@Bean
spring推荐给容器中添加组件的方式

1.配置类:使用全注解的方式

package com.atguigu.springboot.config;

import com.atguigu.springboot.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 指明当前类是一个配置类,来替代spring配置文件
 * 在配置文件中用<bean></bean>标签添加组件
 * 这里使用@bean注解代替
 */
@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中,容器中这个组件默认的id就是该方法名
    @Bean
    public HelloService helloService02() {
        System.out.println("成功给容器添加组件了");
        return new HelloService();
    }
}

2.将之前在主配置启动类中加的注解注释掉(@ImportResource(locations = {“classpath:beans.xml”}))
3.修改测试类中的测试方法

    @Test
    public void testHelloService(){
        boolean b = ioc.containsBean("helloService02");
        System.out.println("helloService result :"+b);
    }

4.测试
在这里插入图片描述

拓展

学习过程中老师只讲了一种配置properties文件的方式,自己尝试了使用yml方式配置,如下:
1.person.yml

person:
  age: 18
  last-name: 毛里求斯
  boss: false
  birth: 2019/10/02
  maps:
    ki: v1
    k2: v2
  list:
    - lisi
    - wangwu
  dog:
    name: 小狗
    age: 2

2.组件–Person类

@PropertySource(value = {"classpath:person.yml"})
@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

3.测试
在这里插入图片描述
都没有拿到值,查了一下是因为@PropertySource默认是properties格式,@PropertySource中存在factory参数,通过配置factory参数可以达到我们想要的效果
4.我们所有做的只需继承DefaultPropertySourceFactory,然后对createPropertySource作下微调,就可以支持yaml了

package com.atguigu.springboot.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.Properties;

public class MixPropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

5.修改配置:
@PropertySource(value = {“classpath:person.yml”}, factory = MixPropertySourceFactory.class)
6.测试
在这里插入图片描述
7.拿到结果了,但是返回的中文转成了Unicode编码,尝试了一圈也没有解决
把配置文件中的显示为unicode编码的字段重新写为中文,再次运行即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值