SpringBoot中@PropertySource和@ImportResource以及@Bean

Genee發表於2018-11-07

@PropertySource

  • 載入指定的配置檔案
  • 只能載入*.properties檔案,不能載入yaml檔案

新建一個user.properties

user.nickname=張三
user.age=19
user.sex=男
user.maps.weight=70
user.maps.height=170
user.address.addr=重慶市渝中區
複製程式碼

UserBean

@Component
@PropertySource(value = {"classpath:user.properties"})
@ConfigurationProperties(prefix = "user")
public class User {

    private String nickname;
    private Integer age;
    private char sex;

    private Map<String,Integer> maps;

    private Address address;
    
    ...
}
複製程式碼

@ImportResource

  • 匯入Spring的配置檔案,讓配置檔案裡面的內容生效

SpringBoot中編寫的Spring配置檔案是不能自動識別的

在主配置類上加入@ImportResource

@ImportResource(locations = {"classpath:beans.xml"})
複製程式碼

SpringBoot給容器新增元件的方式

1、配置類 == Spring配置檔案 通過@Configuration宣告
2、使用@Bean給容器新增元件,元件id預設為方法名

例子

package com.atgenee.demo.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Hello {

    @Bean
    public Hello helloService() {
        System.out.println("新增元件");
        return new Hello();
    }
}
複製程式碼

測試

package com.atgenee.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloServiceApplicationTests {
    
//	@Autowired
//  private Hello hello;
//
//  @Test
//  public void hello() {
//      hello.helloService();
//  }

    @Autowired
    private ApplicationContext ioc;

    @Test
    public void hello() {
        ioc.getBean("helloService");
    }
}

複製程式碼

請注意

若配置類已經加了@Bean註解,此時配置類中的方法名不能跟類名一樣,也就是上面的Hello類中不能定義hello()的方法,否則報錯


通過自定義工廠來實現自定義yaml檔案載入

新建一個cat.yml檔案

cat:
  age: 3
  height: 20
  weight: 5
複製程式碼

工廠類

package com.atgenee.demo.factory;

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

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.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}
複製程式碼

新建配置類 Cat,配合@PropertySource 註解使用

package com.atgenee.demo.config;

import com.atgenee.demo.factory.YamlPropertySourceFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:cat.yml")
@ConfigurationProperties(prefix = "cat")
public class Cat {

    private int age;

    private Double weight;

    private Double height;

    public int getAge() {
        return age;
    }

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

    public Double getWeight() {
        return weight;
    }

    public void setWeight(Double weight) {
        this.weight = weight;
    }

    public Double getHeight() {
        return height;
    }

    public void setHeight(Double height) {
        this.height = height;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "age=" + age +
                ", weight=" + weight +
                ", height=" + height +
                '}';
    }
}
複製程式碼

Cat測試類

package com.atgenee.demo;

import com.atgenee.demo.config.Cat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

    @Autowired
    private Cat cat;

    @Test
    public void hei() {
        System.out.println(cat);
    }

}
複製程式碼

控制檯輸出

Cat{age=3, weight=5.0, height=20.0}
複製程式碼

相關文章