@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 {@Beanpublic 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();
//  }@Autowiredprivate ApplicationContext ioc;@Testpublic 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 {@Overridepublic 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 ignoreResourceNotFoundThrowable 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;}@Overridepublic 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 {@Autowiredprivate Cat cat;@Testpublic void hei() {System.out.println(cat);}}
复制代码

控制台输出

Cat{age=3, weight=5.0, height=20.0}
复制代码

SpringBoot中@PropertySource和@ImportResource以及@Bean相关推荐

  1. SpringBoot配置@PropertySource、@ImportResource、@Bean注解

    引言 @ConfigurationProperties 与@Bean结合为属性赋值 与@PropertySource(只能用properties文件)结合读取指定文件 @Validation 支持使用 ...

  2. 【学习笔记】springBoot中获取sping管理的bean

    文章目录 一.使用场景 二.springBoot中获取sping管理的bean 2.1 生成工具类SpringContextUtil 2.2 使用工具类SpringContextUtil 2.3 注意 ...

  3. SpringBoot_配置-@PropertySource、@ImportResource、@Bean

    前面说了@ConfigurationProperties和@Value的一些区别和用法,我们再来说两个注解,一个叫PropertySource,一个叫@ImportResource,第一个Proper ...

  4. springboot中接口实例化_疫情爆发在家闲出屁的我,梳理一下SpringBoot知识点

    在过去两三年的Spring生态圈,最让人兴奋的莫过于Spring Boot框架.或许从命名上就能看出这个框架的设计初衷:快速的启动Spring应用.因而Spring Boot应用本质上就是一个基于Sp ...

  5. springboot中获取bean_最新Spring Boot干货总结(超详细,建议收藏)

    前言:本文非常长,建议先mark后看,也许是最后一次写这么长的文章说明:前面有4个小节关于Spring的基础知识 分别是:IOC容器.JavaConfig.事件监听.SpringFactoriesLo ...

  6. java filter注入,Spring-boot中Filter注入bean

    Spring-boot中Filter注入bean 在spring中使用Filter的方式不用再多说,但是通常情况下我们在使用filter中都可能会注入部分配置的类或者部分具有特殊功能的业务类. 在这种 ...

  7. SpringBoot中Bean按条件装配

    @Conditional条件装配 @Conditional是Spring Framework提供的一个核心功能注解,这个注解的作用是提供自动装配的条件限制,一般我们在用@Configuration,@ ...

  8. java懒加载注解_在springboot中实现个别bean懒加载的操作

    懒加载---就是我们在spring容器启动的是先不把所有的bean都加载到spring的容器中去,而是在当需要用的时候,才把这个对象实例化到容器中. @Lazy 在需要懒加载的bean上加上@Lazy ...

  9. 如何正确控制springboot中bean的加载顺序总结

    1.为什么需要控制加载顺序 springboot遵从约定大于配置的原则,极大程度的解决了配置繁琐的问题.在此基础上,又提供了spi机制,用spring.factories可以完成一个小组件的自动装配功 ...

最新文章

  1. android 跳转到应用市场
  2. java培训机构_java编程软件培训机构
  3. 简单是一种美:提高项目成功率的一些方法
  4. css设置最小宽度消失,关于CSS:最小/最大宽度媒体查询没有语法意义
  5. ASP.NET创建文件并写入内容
  6. 北大青鸟消防设备类型编码_探测器该如何编码?即报警区域、探测区域的真正用途...
  7. zabbix监控系统时间的问题
  8. 感性精品高清PSD美手分层海报,一键替换,奢华品、首饰、护肤品推荐临摹应用
  9. Enterprise Library引起的A reference to 'System.Design' could not be added
  10. 使用C#代码实现增加用户帐号
  11. Sublime Text实现代码自动生成,快速编写HTML/CSS代码
  12. Python实现pdf转word
  13. matlab怎么输出坐标轴,怎样将matlab图像里面的x,y坐标轴的数据输出
  14. 制作一份高质量的APP运营推广方案
  15. eclipse更改java版本
  16. mysql按首字母查询_按照首字母搜索功能(mysql数据库执行语句)
  17. html网页比赛演讲稿,故事大王比赛的演讲稿范文(精选5篇)
  18. Oracle索引梳理系列(七)- Oracle唯一索引、普通索引及约束的关系
  19. buuctf:Dest0g3 520迎新赛 web EasySSTI
  20. 35佳以字体为核心的优秀网页设计作品

热门文章

  1. KUDU--秒级查询的数据仓库
  2. android 跳转到小米手机神隐模式
  3. Linux 下gedit编辑器的使用
  4. arcgis server发布地图服务中文标注不能显示
  5. Java集合—PriorityQueue底层原理
  6. FONT Awesome 图标
  7. 【TweenMax】实例TimelineMax
  8. (原创)c#学习笔记05--变量的更多内容01--类型转换01--隐式转换
  9. HTML当中特殊字符的表示
  10. XAML实例教程系列 - 命名空间(NameSpace) 三