spring-boot学习四:spring boot配置@PropertySource、@ImportResource、@Bean

1.@PropertySource:导入指定配置文件

我们前面看到的加载配置信息的时候,前提是我们将配置信息都写在了spring boot的全局配置文件application.properties(或者application.yaml)文件中。spring boot还为我们准备了导入指定配置文件的注解@PropertySource;

1.1使用示例

  • 建立一个Student类,里面有stuName、stuAge、className三个属性;
package com.hai.bao.springboot03;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @author :haibao.wang
 * @date :Created in 2019/8/31 22:02
 * @description:使用@PropertySource加载指定配置文件示例
 * @modified By:
 * @version: $
 */
@PropertySource(value = {"classpath:student.properties"})
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
    private String stuName;
    private int stuAge;
    private String className;//班级


    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public int getStuAge() {
        return stuAge;
    }

    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuName='" + stuName + '\'' +
                ", stuAge=" + stuAge +
                ", className='" + className + '\'' +
                '}';
    }
}
  • 新建配置文件student.properties文件,里面设置属性值;

  • 给Student类增加@PropertySource、@Configurationproperties注解,使得可以读取到student.properties配置文件;

 

  • 运行程序,可以正常获取到student.properties文件中的属性值;

2.@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效

这个注解实际上就是导入bean.xml的文件的注解,下面通过实例演示下其用法;

  • 新建一个类HelloService

 

  •  新建一个bean.xml文件,进行ioc配置;
<?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.hai.bao.springboot03.HelloService"></bean>
</beans>

  •  因为Spring boot里面没有加载spring配置文件的功能,所以想要加载进来,需要将@ImportResource注解加到一个配置类上,这个配置类可以是spring boot的主配置类(后者叫主运行类);

 语法为:@ImportResource(locations={"文件1","文件2"});

  • 我们写一个单元测试类测试下;

 3.spring boot推荐的加载spring配置文件的方式

相对于@ImportResource注解加载spring配置文件的方式,spring boot有自身推荐的加载方式,即全注解的方式加载spring配置文件;

既使用配置类:去代替配置文件(即bean.xml配置文件)

  • 新建一个配置类 ,用来代替spring的.xml配置文件

  • 容器中包含的实例名字就是我们配置类中的方法名称;

 当容器中的名称与方法名称不一致的时候,运行为false;

猜你喜欢

转载自www.cnblogs.com/haibaowang/p/11440744.html