SpringBoot學習筆記(4)——@PropertiesSource和@ImportResource

前文我們講了@ConfigurationProperties和@Value來注入配置文件中的屬性值,但是,有一個問題,當我們使用前兩個方法都是通過將配置信息全部寫在一個配置文件application.properties中,當要配置的信息較多時,改配置溫江就顯得很臃腫了。所以,本文我們再使用另一個方法來實現,就是通過@PropertiesSource和@ImportResource註解實現。

1、@PropertiesSource

我們可以單獨創建不同的內容的配置文件,然後通過@PropertiesSource(Value = {"classpath:配置文件名"})的方式來獲取指定的配置文件的屬性值。

配置文件:

person.lastName=張三
person.age=18
person.address=南京
person.dog.name=小花
person.dog.nage=8

需要注入的javabean:

import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


@PropertySource(value={"classpath:person.properties"})
@Component
public class Person {
    
    private String name;
    
    private int age;
    
    private String address;

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getAddress() {
        return address;
    }


}

2、@ImportResource

導入Spring的配置文件,讓配置文件裏面的內容生效;如Spring Boot裏面沒有Spring的配置文件,這時即使我們自己編寫的配置文件,也不能自動識別; 要想讓Spring的配置文件生效,加載進來;需要將@ImportResource標註在一個配置類上。

使用方法:

@ImportResource(locations = {"classpath:beans.xml"})
導入Spring的配置文件讓其生效

自定義的Spring配置文件:

<?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.com.springboot.service.HelloService"></bean>

</beans>

SpringBoot推薦使用全註解的方式來給容器中添加組件:

1、配置類@Configuration——>Spring配置文件

2、使用@Bean給容器中添加組件

/**
* @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件
* 在配置文件中用<bean><bean/>標籤添加組件
*/
@Configuration
public class MyAppConfig {

    //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
    @Bean
    public HelloService helloService02(){

        System.out.println("配置類@Bean給容器中添加組件了...");
        return new HelloService();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章