SpringBoot —— 注入数据的方式

淩亂°似流年 2023-07-16 15:55 101阅读 0赞

关于注入数据说明

format_png

方式一:不通过配置文件注入数据(@Value注解实现)

通过@Value将外部的值动态注入到Bean中,使用的情况有:

  • 注入普通字符串
  • 注入操作系统属性
  • 注入表达式结果
  • 注入其他Bean属性:注入Student对象的属性name
  • 注入文件资源
  • 注入URL资源

辅助代码

  1. package com.hannpang.model;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.stereotype.Component;
  4. @Component(value = "st")//对student进行实例化操作
  5. public class Student {
  6. @Value("悟空")
  7. private String name;
  8. public String getName() {
  9. return name;
  10. }
  11. public void setName(String name) {
  12. this.name = name;
  13. }
  14. }

测试@Value的代码

  1. package com.hannpang.model;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.core.io.Resource;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class SimpleObject {
  7. @Value("注入普通字符串")
  8. private String normal;
  9. //关于属性的KEY可以查看System类说明
  10. @Value("#{systemProperties['java.version']}")//-->使用了SpEL表达式
  11. private String systemPropertiesName; // 注入操作系统属性
  12. @Value("#{T(java.lang.Math).random()*80}")//获取随机数
  13. private double randomNumber; //注入表达式结果
  14. @Value("#{1+2}")
  15. private double sum; //注入表达式结果 1+2的求和
  16. @Value("classpath:os.yaml")
  17. private Resource resourceFile; // 注入文件资源
  18. @Value("http://www.baidu.com")
  19. private Resource testUrl; // 注入URL资源
  20. @Value("#{st.name}")
  21. private String studentName;
  22. //省略getter和setter方法
  23. @Override
  24. public String toString() {
  25. return "SimpleObject{" +
  26. "normal='" + normal + '\'' +
  27. ", systemPropertiesName='" + systemPropertiesName + '\'' +
  28. ", randomNumber=" + randomNumber +
  29. ", sum=" + sum +
  30. ", resourceFile=" + resourceFile +
  31. ", testUrl=" + testUrl +
  32. ", studentName='" + studentName + '\'' +
  33. '}';
  34. }
  35. }

Spring的测试代码

  1. package com.hannpang;
  2. import com.hannpang.model.SimpleObject;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. @RunWith(SpringRunner.class)
  9. @SpringBootTest
  10. public class Demo04BootApplicationTests {
  11. @Autowired
  12. private SimpleObject so;
  13. @Test
  14. public void contextLoads() {
  15. System.out.println(so);
  16. }
  17. }

运行结果为:SimpleObject{normal=’注入普通字符串’, systemPropertiesName=’1.8.0_172’, randomNumber=56.631954541947266, sum=3.0, resourceFile=class path resource [os.yaml], testUrl=URL [http://www.baidu.com\], studentName=’悟空’}

方式二:通过配置文件注入数据

通过@Value将外部配置文件的值动态注入到Bean中。配置文件主要有两类:

application.properties、application.yaml application.properties在spring boot启动时默认加载此文件

自定义属性文件。自定义属性文件通过@PropertySource加载。@PropertySource可以同时加载多个文件,也可以加载单个文件。如果相同第一个属性文件和第二属性文件存在相同key,则最后一个属性文件里的key起作用。加载文件的路径也可以配置变量,如下文的${anotherfile.configinject},此值定义在第一个属性文件config.properties

在application.properties中加入如下测试代码

  1. app.name=一步教育

在resources下面新建第一个属性文件config.properties内容如下

  1. book.name=西游记
  2. anotherfile.configinject=system

在resources下面新建第二个属性文件config_system.properties内容如下

我的目的是想system的值使用第一个属性文件中定义的值

  1. book.name.author=吴承恩

下面通过@Value(“${app.name}”)语法将属性文件的值注入bean属性值,详细代码见:

  1. package com.hannpang.test;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.context.annotation.PropertySource;
  5. import org.springframework.core.env.Environment;
  6. import org.springframework.stereotype.Component;
  7. @Component
  8. @PropertySource(value = {"classpath:config.properties","classpath:config_${anotherfile.configinject}.properties"})
  9. public class LoadPropsTest {
  10. @Value("${app.name}")
  11. private String appName; // 这里的值来自application.properties,spring boot启动时默认加载此文件
  12. @Value("${book.name}")
  13. private String bookName; // 注入第一个配置外部文件属性
  14. @Value("${book.name.author}")
  15. private String author; // 注入第二个配置外部文件属性
  16. @Autowired
  17. private Environment env; // 注入环境变量对象,存储注入的属性值
  18. //省略getter和setter方法
  19. public void setAuthor(String author) {
  20. this.author = author;
  21. }
  22. @Override
  23. public String toString(){
  24. StringBuilder sb = new StringBuilder();
  25. sb.append("bookName=").append(bookName).append("\r\n")
  26. .append("author=").append(author).append("\r\n")
  27. .append("appName=").append(appName).append("\r\n")
  28. .append("env=").append(env).append("\r\n")
  29. // 从eniroment中获取属性值
  30. .append("env=").append(env.getProperty("book.name.author")).append("\r\n");
  31. return sb.toString();
  32. }
  33. }

测试代码

  1. package com.hannpang;
  2. import com.hannpang.model.SimpleObject;
  3. import com.hannpang.test.LoadPropsTest;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. @RunWith(SpringRunner.class)
  10. @SpringBootTest
  11. public class Demo04BootApplicationTests {
  12. @Autowired
  13. private LoadPropsTest lpt;
  14. @Test
  15. public void loadPropertiesTest() {
  16. System.out.println(lpt);
  17. }
  18. }

运行结果为:
bookName=西游记
author=吴承恩
appName=一步教育
env=StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[ConfigurationPropertySourcesPropertySource {name=’configurationProperties’}, MapPropertySource {name=’Inlined Test Properties’}, MapPropertySource {name=’systemProperties’}, OriginAwareSystemEnvironmentPropertySource {name=’systemEnvironment’}, RandomValuePropertySource {name=’random’}, OriginTrackedMapPropertySource {name=’applicationConfig: [classpath:/application.properties]‘}, ResourcePropertySource {name=’class path resource [config_system.properties]‘}, ResourcePropertySource {name=’class path resource [config.properties]‘}]}
env=吴承恩

#{…}和${…}的区别演示

A.${…}的用法

{}里面的内容必须符合SpEL表达式,通过@Value(“${app.name}”)可以获取属性文件中对应的值,但是如果属性文件中没有这个属性,则会报错。可以通过赋予默认值解决这个问题,如@Value("${app.name:胖先森}")

部分代码

  1. // 如果属性文件没有app.name,则会报错
  2. // @Value("${app.name}")
  3. // private String name;
  4. // 使用app.name设置值,如果不存在则使用默认值
  5. @Value("${app.name:胖先森}")
  6. private String name;

B.#{…}的用法

部分代码直接演示

  1. // SpEL:调用字符串Hello World的concat方法
  2. @Value("#{'Hello World'.concat('!')}")
  3. private String helloWorld;
  4. // SpEL: 调用字符串的getBytes方法,然后调用length属性
  5. @Value("#{'Hello World'.bytes.length}")
  6. private String helloWorldbytes;

C.#{…}和${…}混合使用

${...}#{...}可以混合使用,如下文代码执行顺序:通过${server.name}从属性文件中获取值并进行替换,然后就变成了 执行SpEL表达式{‘server1,server2,server3’.split(‘,’)}

  1. // SpEL: 传入一个字符串,根据","切分后插入列表中, #{}和${}配置使用(注意单引号,注意不能反过来${}在外面,#{}在里面)
  2. @Value("#{'${server.name}'.split(',')}")
  3. private List<String> servers;

在上文中在#{}外面,${}在里面可以执行成功,那么反过来是否可以呢${}在外面,#{}在里面,如代码

  1. // SpEL: 注意不能反过来${}在外面,#{}在里面,这个会执行失败
  2. @Value("${#{'HelloWorld'.concat('_')}}")
  3. private List<String> servers2;

答案是不能。

因为spring执行${}是时机要早于#{}。

在本例中,Spring会尝试从属性中查找#{‘HelloWorld’.concat(‘_’)},那么肯定找到,由上文已知如果找不到,然后报错。所以${}在外面,#{}在里面是非法操作

D.用法总结

  • #{…} 用于执行SpEl表达式,并将内容赋值给属性
  • ${…} 主要用于加载外部属性文件中的值
  • #{…}${…} 可以混合使用,但是必须#{}外面,${}在里面

@Value获取值和@ConfigurationProperties获取值比较

format_png 1

配置文件yml还是properties他们都能获取到值;

  • 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
  • 如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;

关于数据校验的部分代码

  1. @Component
  2. @ConfigurationProperties(prefix = "person")
  3. @Validated
  4. public class Person {
  5. //lastName必须是邮箱格式
  6. @Email
  7. private String lastName;

@ImportResource引入配置文件(不推荐的使用方式)

Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;

想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

  1. @ImportResource(locations = {"classpath:beans.xml"})

导入Spring的配置文件让其生效,编写配置文件信息

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="helloService" class="com.hanpang.springboot.service.HelloService"></bean>
  6. </beans>

大概了解就好,我们基本上不使用这种方式

@Configuration注解

SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式

  • 配置类@Configuration作用于类上,相当于一个xml配置文件
  • 使用@Bean给容器中添加组件,作用于方法上

    /**

    • @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
      *
    • 在配置文件中用标签添加组件

    • */
      @Configuration
      public class MyAppConfig {

      //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
      @Bean
      public HelloService helloService02(){

      1. System.out.println("配置类@Bean给容器中添加组件了...");
      2. return new HelloService();

      }
      }

使用Bean注入太麻烦,我们更加喜欢使用扫描的方式

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import com.wx.dao.IUserDao;
  5. import com.wx.dao.UserDaoImpl;
  6. //通过该注解来表明该类是一个Spring的配置,相当于一个传统的ApplicationContext.xml
  7. @Configuration
  8. //相当于配置文件里面的<context:component-scan/>标签,扫描这些包下面的类的注解
  9. @ComponentScan(basePackages="com.hanpang.dao,com.hanpang.service")
  10. public class SpringConfig {
  11. // 通过该注解来表明是一个Bean对象,相当于xml中的<bean>
  12. //bean的id值默认是方法名userDao
  13. /*
  14. @Bean
  15. public HelloService helloService02(){
  16. System.out.println("配置类@Bean给容器中添加组件了...");
  17. return new HelloService();
  18. }
  19. */
  20. }

附录

随机数

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

发表评论

表情:
评论列表 (有 0 条评论,101人围观)

还没有评论,来说两句吧...

相关阅读