组件管理 + 属性注入

  • 组件管理
    • @Component 管理单个组件
    • @Configuration + @Bean 管理多个组件
  • 属性注入
    • 基本属性注入 @Value
    • 对象方式注入 @ConfigurationProperties
    • 两种注入方式比较
    • 注入细节
      • 配置文件注入值数据校验 @Validated
      • 加载指定的配置文件 @PropertySource
      • 导入 Spring 的配置文件 @ImportResource
      • 配置文件占位符

SpringBoot 核心知识点整理!

组件管理

@Component 管理单个组件

在 springboot 中可以管理自定义的 简单组件 对象的创建可以直接使用注解形式创建:

  • @Component 用来管理单个组件(包扫描形式)

1、使用 @Repository@Service@Controller、以及 @Component 管理不同简单对象;
比如要通过工厂创建自定义 User 对象:User.java

@Component
@Data
public class User {private String id;private String name;// ......
}

2、通过工厂创建之后可以在使用处任意注入该对象;
比如在控制器中使用自定义简单对象创建:

@Controller
@RequestMapping("hello")
public class HelloController {@Autowiredprivate User user;// ......
}

@Configuration + @Bean 管理多个组件

在 springboot 中如果要管理 复杂对象 必须使用 @Configuration + @Bean 注解进行管理;

  • @Configuration 主要用来生产多个组件交给工厂管理 (注册形式)

1、管理复杂对象的创建
注意:这里的 User 不需要加 @Component 注解,与上面的管理单个对象区分开来。

@ToString
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {private String id;private String name;
}
@Configuration // @Component 也可以, 不推荐
public class BeanConfigs {@Bean   // @Bean 将当前返回值作为工厂中的一个对象进行管理public User getUser() {return new User();}@Bean //(name = "aaa") // 用来将该方法的返回值交给springboot管理 在工厂中默认标识: 类名(首字母小写)@Scope("prototype") // prototype表示多例; 默认是singleton, 单例的public Calendar getCalendar() {return Calendar.getInstance();}}

2、使用复杂对象

@RestController
@RequestMapping("/hello")
public class HelloController {@Autowiredprivate User user;@Autowiredprivate Calendar calendar1;@Autowiredprivate Calendar calendar2;@GetMapping("/hello")public String hello() {System.out.println(user); // 管理单个对象// 管理多个对象, 默认是单例的, 需要设置 prototypeSystem.out.println(calendar1.getTime()); // 成功创建出对象System.out.println(calendar1 == calendar2); // 默认是单例的, 需要设置 prototype 才为多例return "hello spring boot!!!";}

属性注入

SpringBoot 使用一个全局的配置文件,配置文件名是固定的:

  • application.properties
  • application.yml

配置文件的作用:修改 SpringBoot 自动配置的默认值;SpringBoot 在底层都给我们自动配置好了;

springboot 中提供了两种注入方式:基本属性注入对象注入

基本属性注入 @Value

基本属性包括:intStringDateString[]ListMap 等。

基本属性注入:使用注解 @Value("${xxx}")

@RestController
@RequestMapping("hello")
public class HelloController {@Value("${server.port}") private int port;@Value("${str}") private String str;@Value("${bir}")private Date bir;@Value("${strs}")private String[] strs;@Value("${list}")private List<String> list;@Value("#{${maps}}") // map注入取值有点特殊private Map<String, String> maps;@GetMapping("hello")public String hello() {// port = 8989System.out.println("port = " + port);// str =  zhenyuSystem.out.println("str= " + str);// time = Wed Dec 12 12:12:12 CST 2012System.out.println("time = " + bir);// aa// bb// ccfor (String str : strs) {System.out.println(str);}// zhangsan// lisi// wangwulist.forEach( v -> System.out.println(v));// k = aa, v = xiaoyi// k = bb, v = xiaoer// k = cc, v = xiaosanmaps.forEach((k, v) -> {System.out.println("k = " + k + ", v = " + v);});return "hello spring boot!";}
}

application.properties 中配置:

server.port = 8989# 属性注入
str = zhenyu
bir = 2012/12/12 12:12:12strs = aa, bb, cc
list = zhangsan, lisi, wangwu
maps = {'aa':'xiaoyi', 'bb':'xiaoer', 'cc':'xiaosan'}

对象方式注入 @ConfigurationProperties

对象方式注入使用注解:@ConfigurationProperties(prefix="前缀")

@ConfigurationProperties 告诉 SpringBoot 本类中的所有属性在配置文件中进行绑定;

  • 只有这个组件是容器中的组件,才能容器提供的 @ConfigurationProperties 功能,所以需要 @Component
@ToString
@Data // 必要
@Component // @Configuration 也可以
@ConfigurationProperties(prefix = "user") // 必要
public class User {private String id;private String name;private Integer age;private Date bir;
}

控制器中使用:@Autowired 完成自动注入;

@RestController
@RequestMapping("hello")
public class HelloController {@Autowiredprivate User user;@GetMapping("hello")public String hello() {System.out.println(user); // User(id=1721, name=yusael, age=20, bir=Wed Dec 12 12:12:12 CST 2012)return "hello spring boot!";}
}

application.properties 中配置:

# 自定义对象属性注入
user.id = 1721
user.name = zhenyu
user.age = 20
user.bir = 2012/12/12 12:12:12

注:可以通过引入依赖 —— 配置文件处理器,构建自定义注入元数据。

  • 意思就是引入这个依赖后,在 配置文件中写注入对象会有提示,不引入也不影响什么。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional>
</dependency>

两种注入方式比较

@ConfigurationProperties @Value
功能 批量注入配置文件中的属性 一个个指定
松散绑定(松散语法) 支持 不支持
SpEL 不支持 支持
JSR303 数据校验 支持 不支持
复杂类型封装 支持 不支持

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用 @Value

如果说,我们专门编写了一个 javaBean 来和配置文件进行映射,我们就直接使用@ConfigurationProperties

注入细节

配置文件注入值数据校验 @Validated

@Component
@ConfigurationProperties(prefix = "person")
@Validated // 配置文件注入值数据校验
public class Person {/*** <bean class="Person">*      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>* <bean/>*///lastName必须是邮箱格式@Email//@Value("${person.last-name}")private String lastName;//@Value("#{11*2}")private Integer age;//@Value("true")private Boolean boss;private Date birth;private Map<String,Object> maps;private List<Object> lists;private Dog dog;

加载指定的配置文件 @PropertySource

@PropertySource 加载指定的配置文件;

// 加载指定的配置文件
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {private String lastName;private Integer age;private Boolean boss;
}

导入 Spring 的配置文件 @ImportResource

@ImportResource:导入 Spring 的配置文件,让配置文件里面的内容生效;

  • Spring Boot 里面没有 Spring 的配置文件,我们自己编写的配置文件,也不能自动识别;
    想让 Spring 的配置文件生效,加载进来;@ImportResource 标注在一个配置类上;
// 导入Spring的配置文件让其生效
@ImportResource(locations = {"classpath:beans.xml"})

然后编写 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.atguigu.springboot.service.HelloService"></bean>
</beans>

配置文件占位符

随机数:

${random.uuid}
${random.value}
${random.int}
${random.long}
${random.int(10)}
${random.int[1024,65536]}

: 指定占位符中的默认值:

person.last-name=张三${random.uuid} # 随机数
person.age=${random.int} # 随机数
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog # 指定默认值
person.dog.age=15

【SpringBoot 】 组件管理 + 属性注入相关推荐

  1. spring项目属性注入和bean管理xml 注入一般属性和集合属性

    IOC 介绍: 在Spring的应用中,Spring IoC容器可以创建.装配和配置应用组件对象,这里的组件对象称为Bean. Bean的实例化 在面向对象编程中,想使用某个对象时,需要事先实例化该对 ...

  2. Spring——Bean管理-xml方式进行属性注入

    目录 一.xml方式创建对象 二.xml方式注入属性 第①种方式注入:set方法注入 第②种方式注入:有参构造函数注入 constructor-arg:通过构造函数注入 用name标签属性: 不按照顺 ...

  3. springboot属性注入

    SpringBoot的属性注入 在上面的案例中,我们实验了java配置方式.不过属性注入使用的是@Value注解.这种方式虽然可行,但是不够强大,因为它只能注入基本类型值. 在SpringBoot中, ...

  4. springboot的yaml属性配置文件注入

    SpringBoot中默认的从application.properties文件中加载参数 我们通常把springboot中资源目录下的application.properties文件改成applica ...

  5. springboot属性注入的四种方法

    springBoot属性注入的四种方法: 以注入jdbc数据源为例 1.首先在resources下面创建application.properties文件,并添加jdbc数据源属性 jdbc.drive ...

  6. springboot属性注入的四种方式

    springboot属性注入 1.前言:介绍以前spring中配置 java配置主要靠java类和一些注解来达到和xml配置一样的效果,比较常用的注解有: @Configuration:声明一个类作为 ...

  7. SpringBoot 属性注入的四种方式

    一.Spring的属性注入方式(以前的方式) java配置主要靠java类和一些注解来达到和xml配置一样的效果,比较常用的注解有: @Configuration:声明一个类作为配置类,代替xml文件 ...

  8. druiddatasource配置_Springboot属性注入 Java配置和Value配置

    今天我们正式进入了SpringBoot入门实战系列的课程,第二个部分SpringBoot配置和日志管理,本期课程将会分享:1.springboot属性注入 - @Value(推荐);2.Springb ...

  9. Spring(三)——HelloSpring、IOC创建对象的方式、属性注入、自动装配、使用注解开发

    文章目录 1. 简介 2. IOC理论推导 3. HelloSpring 4. IOC创建对象的方式 4.1 使用无参构造创建对象(默认) 4.2 使用有参构造创建对象 5. Spring配置 5.1 ...

最新文章

  1. CUDA C++程序设计模型
  2. 人工智能入门:keras的example文件解析
  3. java验证码源码_Java通用验证码程序及应用示例(提供源码下载)
  4. linux环境变量堆栈,情景linux--如何摆脱深路径的频繁切换烦恼?
  5. 最近很火的 ClickHouse 是什么?
  6. 系统制成docker镜像_Docker学习以及镜像制作流程
  7. c# 通过字体对话框获取字体名称和字体大小_PS插件神器 :fonTags,超好用的PS字体管理插件(附安装方法)
  8. 用Python解决数据结构与算法问题
  9. Mac Nginx 配置 Tomcat 配置 jdk环境变量 Nginx部署服务遇到的坑(3)
  10. mysql float 误差_mysql下float类型使用一些误差详解
  11. Redis视频教程免费下载
  12. 轴承的Abaqus静态分析
  13. 人教版四年级上次计算机教案,人教版四年级上册数学教案
  14. 拉绳位移传感器的原理
  15. 带有风的诗词_带有风的诗句
  16. Windows 10语言栏消失不见了的解决办法
  17. 《新零售 低价高效的数据赋能之路》读后感
  18. 使用drbd实现数据的高可用
  19. 诺基亚获得首个5G大规模订单,全球正式开启5G争夺战!
  20. R实战:【股票分析】用quantmod在股票的K线上添加标记

热门文章

  1. 自媒体新手拍视频从哪开始入手?
  2. 程序员的工资普遍在20k以上
  3. 为什么很多人赚不到钱?
  4. 如果微信被运维删库、跑路,会造成什么恐怖的后果?
  5. Mybatis_day2_Mybatis的参数深入
  6. git bitbucket_如何在Bitbucket上创建新的Git存储库并查看提交的对象
  7. Socket超时时间设置
  8. Linux 期中架构 inotify
  9. 关于徒手脱壳的几种方法
  10. VS2005迁移项目工程所带来问题