咱们前面看到的加载配置信息的时候,前提是咱们将配置信息都写在了spring boot的全局配置文件application.properties(或者application.yaml)文件中。spring boot还为咱们准备了导入指定配置文件的注解@PropertySource;spring
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 + '\'' + '}'; } }
这个注解实际上就是导入bean.xml的文件的注解,下面经过实例演示下其用法;springboot
<?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>
语法为:@ImportResource(locations={"文件1","文件2"});app
相对于@ImportResource注解加载spring配置文件的方式,spring boot有自身推荐的加载方式,即全注解的方式加载spring配置文件;ide
既使用配置类:去代替配置文件(即bean.xml配置文件)单元测试
当容器中的名称与方法名称不一致的时候,运行为false;测试