全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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}

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


# spring  # boot  # 注入bean  # 属性注入  # bean属性注入  # 在SpringBoot下读取自定义properties配置文件的方法  # Springboot如何通过自定义工具类获取bean  # java SpringBoot自定义注解  # 及自定义解析器实现对象自动注入操作  # springboot如何读取自定义properties并注入到bean中  # 配置文件  # 返回值  # 类似于  # 类中  # 的是  # 测试一下  # 是一个  # 自动加载  # 才会  # 这是一个  # 这就  # 就不能  # 作为一个  # 要将  # 第三方  # 不加  # 进去了  # 创建一个  # 第二部分  # 大家多多 


相关文章: 已有域名和空间,如何快速搭建网站?  建站168自助建站系统:快速模板定制与SEO优化指南  建站之星ASP如何实现CMS高效搭建与安全管理?  如何在云主机上快速搭建网站?  如何在Golang中使用replace替换模块_指定本地或远程路径  C#怎么创建控制台应用 C# Console App项目创建方法  定制建站哪家更专业可靠?推荐榜单揭晓  济南企业网站制作公司,济南社保单位网上缴费步骤?  香港网站服务器数量如何影响SEO优化效果?  建站之家VIP精选网站模板与SEO优化教程整合指南  如何在局域网内绑定自建网站域名?  如何在新浪SAE免费搭建个人博客?  linux top下的 minerd 木马清除方法  ,巨量百应是干嘛的?  建站之星展会模版如何一键下载生成?  详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)  如何在建站主机中优化服务器配置?  股票网站制作软件,网上股票怎么开户?  网站制作免费,什么网站能看正片电影?  建站之星安装后如何配置SEO及设计样式?  *服务器网站为何频现安全漏洞?  三星网站视频制作教程下载,三星w23网页如何全屏?  如何用虚拟主机快速搭建网站?详细步骤解析  怎么制作网站设计模板图片,有电商商品详情页面的免费模板素材网站推荐吗?  Python路径拼接规范_跨平台处理说明【指导】  Swift中swift中的switch 语句  英语简历制作免费网站推荐,如何将简历翻译成英文?  logo在线制作免费网站在线制作好吗,DW网页制作时,如何在网页标题前加上logo?  如何在企业微信快速生成手机电脑官网?  活动邀请函制作网站有哪些,活动邀请函文案?  专业商城网站制作公司有哪些,pi商城官网是哪个?  桂林网站制作公司有哪些,桂林马拉松怎么报名?  儿童网站界面设计图片,中国少年儿童教育网站-怎么去注册?  定制建站流程解析:需求评估与SEO优化功能开发指南  微课制作网站有哪些,微课网怎么进?  宝塔面板创建网站无法访问?如何快速排查修复?  非常酷的网站设计制作软件,酷培ai教育官方网站?  如何在IIS中配置站点IP、端口及主机头?  枣阳网站制作,阳新火车站打的到仙岛湖多少钱?  建站之星3.0如何解决常见操作问题?  武汉网站制作费用多少,在武汉武昌,建面100平方左右的房子,想装暖气片,费用大概是多少啊?  建站之星如何开启自定义404页面避免用户流失?  建站主机如何选?高性价比方案全解析  建站OpenVZ教程与优化策略:配置指南与性能提升  如何使用Golang table-driven基准测试_多组数据测量函数效率  建站之星上传入口如何快速找到?  广州商城建站系统开发成本与周期如何控制?  网站制作服务平台,有什么网站可以发布本地服务信息?  网站网页制作电话怎么打,怎样安装和使用钉钉软件免费打电话?  购物网站制作费用多少,开办网上购物网站,需要办理哪些手续? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。