Spring boot将配置属性注入到bean类中

 更新时间:2017年03月02日 11:13:17   作者:heikeyuit  
本篇文章主要介绍了Spring boot将配置属性注入到bean类中,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

一、@ConfigurationProperties注解的使用

看配置文件,我的是yaml格式的配置:

// file application.yml
my:
 servers:
  - dev.bar.com
  - foo.bar.com
  - jiaobuchong.com

下面我要将上面的配置属性注入到一个Java Bean类中,看码:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * file: MyConfig.java
 * Created by jiaobuchong on 12/29/15.
 */
@Component   //不加这个注解的话, 使用@Autowired 就不能注入进去了
@ConfigurationProperties(prefix = "my") // 配置文件中的前缀
public class MyConfig {
  private List<String> servers = new ArrayList<String>();
  public List<String> getServers() { return this.servers;
  }
}

下面写一个Controller来测试一下:

/**
 * file: HelloController
 * Created by jiaobuchong on 2015/12/4.
 */
@RequestMapping("/test")
@RestController
public class HelloController {
  @Autowired
  private MyConfig myConfig;

  @RequestMapping("/config")
  public Object getConfig() {
    return myConfig.getServers();
  }
}

下面运行Application.java的main方法跑一下看看:

@Configuration  //标注一个类是配置类,spring boot在扫到这个注解时自动加载这个类相关的功能,比如前面的文章中介绍的配置AOP和拦截器时加在类上的Configuration


@EnableAutoConfiguration //启用自动配置 该框架就能够进行行为的配置,以引导应用程序的启动与运行, 根据导入的starter-pom 自动加载配置
@ComponentScan //扫描组件 @ComponentScan(value = "com.spriboot.controller") 配置扫描组件的路径
public class Application {
  public static void main(String[] args) {
    // 启动Spring Boot项目的唯一入口
    SpringApplication app = new SpringApplication(Application.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
  }

在浏览器的地址栏里输入:

localhost:8080/test/config 得到:

[“dev.bar.com”,”foo.bar.com”,”jiaobuchong.com”]

二、@ConfigurationProperties和@EnableConfigurationProperties注解结合使用

在spring boot中使用yaml进行配置的一般步骤是,

1、yaml配置文件,这里假设:

my:
 webserver:
  #HTTP 监听端口
  port: 80
  #嵌入Web服务器的线程池配置
  threadPool:
   maxThreads: 100
   minThreads: 8
   idleTimeout: 60000

2、

//file MyWebServerConfigurationProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "my.webserver")
public class MyWebServerConfigurationProperties {
  private int port;
  private ThreadPool threadPool;

  public int getPort() {
    return port;
  }

  public void setPort(int port) {
    this.port = port;
  }

  public ThreadPool getThreadPool() {
    return threadPool;
  }

  public void setThreadPool(ThreadPool threadPool) {
    this.threadPool = threadPool;
  }

  public static class ThreadPool {
    private int maxThreads;
    private int minThreads;
    private int idleTimeout;

    public int getIdleTimeout() {
      return idleTimeout;
    }

    public void setIdleTimeout(int idleTimeout) {
      this.idleTimeout = idleTimeout;
    }

    public int getMaxThreads() {
      return maxThreads;
    }

    public void setMaxThreads(int maxThreads) {
      this.maxThreads = maxThreads;
    }

    public int getMinThreads() {
      return minThreads;
    }

    public void setMinThreads(int minThreads) {
      this.minThreads = minThreads;
    }
  }
}

3、

// file: MyWebServerConfiguration.java
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@Configuration
@EnableConfigurationProperties(MyWebServerConfigurationProperties.class)
public class MyWebServerConfiguration {
  @Autowired
  private MyWebServerConfigurationProperties properties;
  /**
   *下面就可以引用MyWebServerConfigurationProperties类    里的配置了
  */
  public void setMyconfig() {
    String port = properties.getPort();
    // ...........
  }  
}

The @EnableConfigurationProperties annotation is automatically applied to your project so that any beans annotated with @ConfigurationProperties will be configured from the Environment properties. This style of configuration works particularly well with the SpringApplication external YAML configuration.(引自spring boot官方手册)

三、@Bean配置第三方组件(Third-party configuration)

创建一个bean类:

// file ThreadPoolBean.java
/**
 * Created by jiaobuchong on 1/4/16.
 */
public class ThreadPoolBean {
  private int maxThreads;
  private int minThreads;
  private int idleTimeout;

  public int getMaxThreads() {
    return maxThreads;
  }

  public void setMaxThreads(int maxThreads) {
    this.maxThreads = maxThreads;
  }

  public int getMinThreads() {
    return minThreads;
  }

  public void setMinThreads(int minThreads) {
    this.minThreads = minThreads;
  }

  public int getIdleTimeout() {
    return idleTimeout;
  }

  public void setIdleTimeout(int idleTimeout) {
    this.idleTimeout = idleTimeout;
  }
}

引用前面第二部分写的配置类:MyWebServerConfiguration.java和MyWebServerConfigurationProperties.java以及yaml配置文件,现在修改MyWebServerConfiguration.java类:

import com.jiaobuchong.springboot.domain.ThreadPoolBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by jiaobuchong on 1/4/16.
 */
@Configuration //这是一个配置类,与@Service、@Component的效果类似。spring会扫描到这个类,@Bean才会生效,将ThreadPoolBean这个返回值类注册到spring上下文环境中
@EnableConfigurationProperties(MyWebServerConfigurationProperties.class) //通过这个注解, 将MyWebServerConfigurationProperties这个类的配置到上下文环境中,本类中使用的@Autowired注解注入才能生效
public class MyWebServerConfiguration {
  @SuppressWarnings("SpringJavaAutowiringInspection") //加这个注解让IDE 不报: Could not autowire
  @Autowired
  private MyWebServerConfigurationProperties properties;

  @Bean //@Bean注解在方法上,返回值是一个类的实例,并声明这个返回值(返回一个对象)是spring上下文环境中的一个bean
  public ThreadPoolBean getThreadBean() {
    MyWebServerConfigurationProperties.ThreadPool threadPool = properties.getThreadPool();
    ThreadPoolBean threadPoolBean = new ThreadPoolBean();
    threadPoolBean.setIdleTimeout(threadPool.getIdleTimeout());
    threadPoolBean.setMaxThreads(threadPool.getMaxThreads());
    threadPoolBean.setMinThreads(threadPool.getMinThreads());
    return threadPoolBean;
  }
}

被@Configuration注解标识的类,通常作为一个配置类,这就类似于一个xml文件,表示在该类中将配置Bean元数据,其作用类似于Spring里面application-context.xml的配置文件,而@Bean标签,则类似于该xml文件中,声明的一个bean实例。
写一个controller测试一下:

import com.jiaobuchong.springboot.domain.ThreadPoolBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by jiaobuchong on 2015/12/4.
 */
@RequestMapping("/first")
@RestController
public class HelloController {
  @Autowired
  private ThreadPoolBean threadPoolBean;
  @RequestMapping("/testbean")
  public Object getThreadBean() {
    return threadPoolBean;
  }

}

运行Application.java的main方法,

在浏览器里输入:http://localhost:8080/first/testbean

得到的返回值是:

{“maxThreads”:100,”minThreads”:8,”idleTimeout”:60000}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Android 应用按返回键退向后台运行实例代码

    Android 应用按返回键退向后台运行实例代码

    这篇文章主要介绍了Android 应用按返回键退向后台运行实例代码的相关资料,需要的朋友可以参考下
    2017-04-04
  • 基于Springboot一个注解搞定数据字典的实践方案

    基于Springboot一个注解搞定数据字典的实践方案

    这篇文章主要介绍了基于Springboot一个注解搞定数据字典问题,大致的方向是自定义注解,在序列化的时候进行数据处理,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • Java线程池必知必会知识点总结

    Java线程池必知必会知识点总结

    这篇文章主要给大家介绍了关于Java线程池必知必会知识点的相关资料,文中通过图文以及实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2022-02-02
  • java实现多人聊天对话室

    java实现多人聊天对话室

    这篇文章主要为大家详细介绍了java实现多人聊天对话室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • Java基础语法:逻辑控制

    Java基础语法:逻辑控制

    下面小编就为大家带来一篇Java逻辑控制的基础文章。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-08-08
  • Netty分布式抽象编码器MessageToByteEncoder逻辑分析

    Netty分布式抽象编码器MessageToByteEncoder逻辑分析

    这篇文章主要介绍了Netty分布式抽象编码器MessageToByteEncoder的抽象逻辑分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-03-03
  • springboot rabbitmq整合rabbitmq之消息持久化存储问题

    springboot rabbitmq整合rabbitmq之消息持久化存储问题

    这篇文章主要介绍了springboot rabbitmq整合rabbitmq之消息持久化存储问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Java的堵塞队列BlockingQueue详解

    Java的堵塞队列BlockingQueue详解

    这篇文章主要介绍了Java的堵塞队列BlockingQueue详解,阻塞队列常用于生产者和消费者的场景,生产者是向队列里添加元素的线程,消费者是从队列里取元素的线程,需要的朋友可以参考下
    2023-12-12
  • 关于Java反编译字节码文件

    关于Java反编译字节码文件

    将高级语言翻译成汇编语言或机器语言的过程Java语言中的编译一般指将Java文件转换成class文件顾名思义反编译就是编译的逆向过程其实我们常用的开发工具(例如:IDEA、Eclipse)都带有反编译功能,需要的朋友可以参考下
    2023-05-05
  • springboot jackson自定义序列化和反序列化实例

    springboot jackson自定义序列化和反序列化实例

    这篇文章主要介绍了spring boot jackson自定义序列化和反序列化实例,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10

最新评论