SpringBoot中@PropertySource和@ImportResource以及@Bean


@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}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设我们有一个Spring Boot应用程序,需要从外部配置文件加载某些属性。我们可以使用@PropertySource注释将外部属性文件加载到Spring Boot应用程序。 例如,假设我们有一个名为application.properties的属性文件,其包含以下属性: ``` server.port=8080 database.url=jdbc:mysql://localhost:3306/mydb database.username=root database.password=password ``` 我们可以在Spring Boot应用程序使用@PropertySource注释来加载这些属性文件,如下所示: ```java @Configuration @PropertySource("classpath:application.properties") public class AppConfig { @Value("${server.port}") private int serverPort; @Value("${database.url}") private String databaseUrl; @Value("${database.username}") private String databaseUsername; @Value("${database.password}") private String databasePassword; // getters and setters } ``` 在这个示例,我们使用@Configuration注释将类标记为配置类,并使用@PropertySource注释将属性文件加载到Spring Boot应用程序。我们还使用@Value注释将属性值注入到应用程序的变量。 现在,我们可以使用这些属性来配置我们的应用程序,如下所示: ```java @SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } @Autowired private AppConfig appConfig; @Bean public TomcatServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.setPort(appConfig.getServerPort()); return tomcat; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl(appConfig.getDatabaseUrl()); dataSource.setUsername(appConfig.getDatabaseUsername()); dataSource.setPassword(appConfig.getDatabasePassword()); return dataSource; } } ``` 在这个示例,我们使用@Autowired注释将AppConfig类注入到MyApp类,然后使用属性值来配置Tomcat服务器和数据源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值