咱們前面看到的加載配置信息的時候,前提是咱們將配置信息都寫在了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;測試