Spring Boot通过注解实现属性注入详解

使用 Spring Boot 全局配置文件设置属性时:
如果配置属性是 Spring Boot 已有属性,例如服务端口 server.port ,那么 Spring Boot 内部会自动扫描并读取这些配置文件中的属性值并覆盖默认属性。
如果配置的属性是用户自定义属性,例如刚刚自定义的 Person 实体类属性,还必须在程序中注入这些配置属性方可生效。

一. 属性注入常用注解

@Configuration :声明一个类作为配置类
@Bean :声明在方法上,将方法的返回值加入 Bean 容器
@Value :属性注入
@ConfigurationProperties(prefix = "jdbc") :批量属性注入
@PropertySource("classpath:/jdbc.properties") 指定外部属性文件。在类上添加

二. @Value属性值注入

(一).引入数据源连接依赖

<dependency>
            <groupId>com.github.drtrang</groupId>
            <artifactId>druid-spring-boot2-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

(二)application.properties添加信息

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc : mysql : //127.0.0.1 : 3306/springboot_h
jdbc.username = root
jdbc.password = 123

(三)配置数据源

创建 JdbcConfiguration 类: 使用 spring 中的 value 注解对每个属性进行注入 , bean 注解将返回值添加到容器中
@Configuration public class JdbcConfiguration { 
    @Value("${jdbc.url}") 
    String url; 
    @Value("${jdbc.driverClassName}") 
    String driverClassName; 
    @Value("${jdbc.username}") 
    String username; 
    @Value("${jdbc.password}") 
    String password; 
    
    
    @Bean 
    public DataSource dataSource() { 
        DruidDataSource dataSource = new DruidDataSource(); 
        dataSource.setUrl(url); 
        dataSource.setDriverClassName(driverClassName); 
        dataSource.setUsername(username); 
        dataSource.setPassword(password); 
        return dataSource; 
    } 
}

三. @ConfigurationProperties批量注入

@ConfigurationProperties(prefix = "jdbc")//这里需要定义出在application文件中定义属 性值得前缀信息
public class JdbcConfiguration {

    private String driverClassName;

    private String url;

    private String username;

    private String password;

    // 注:要生成属性的set方法
}
注:添加 @ConfigurationProperties 注解后有警告: springboot 配置注释处理器未配置(编写配置文件此时无提示)

添加spring-boot-configuration-processor后出现提示,加完依赖后通过Ctrl+F9来使之生效  

接着发现,仍然有红色警告

 

@EnableConfigurationProperties Spring Boot 提供的一个注解,使用该注解用于启用应用对另
外一个注解 @ConfigurationProperties 的支持,,用于设置一组使用了注解
@ConfigurationProperties 的类 , 用于作为 bean 定义注册到容器中。

 application.properties添加信息

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc : mysql : //127.0.0.1 : 3306/springboot_h
jdbc.username = root
jdbc.password = 123

注意:将配置信息添加到这里,通过前缀进行区分,进行引用

四. 第三方配置

除了 @ConfigurationProperties 用于注释类之外,您还可以在公共 @Bean 方法上使用它。当要将属性绑定到控件之外的第三方组件时,这样做特别有用。
创建一个其他组件类
package com.lagou.pojo;

import java.net.InetAddress;


public class AnotherComponent {

    // 是否启用
    private Boolean enabled;

    // IP地址
    private InetAddress remoteAddress;

    public Boolean getEnabled() {
        return enabled;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    public InetAddress getRemoteAddress() {
        return remoteAddress;
    }

    public void setRemoteAddress(InetAddress remoteAddress) {
        this.remoteAddress = remoteAddress;
    }

    @Override
    public String toString() {
        return "AnotherComponent{" +
                "enabled=" + enabled +
                ", remoteAddress=" + remoteAddress +
                '}';
    }
}
创建 MyService
package com.lagou.config;

import com.lagou.pojo.AnotherComponent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyService {


    @ConfigurationProperties(prefix = "another")
    @Bean
    public AnotherComponent anotherComponent(){
        return new AnotherComponent();
    }


}
配置文件
another.enabled=true
another.remoteAddress=192.168.1.11
测试类
    @Autowired
    private AnotherComponent anotherComponent;

    @Test
    public void test2(){
        System.out.println(anotherComponent);
    }

五. 松散绑定

Spring Boot 使用一些宽松的规则将环境属性绑定到 @ConfigurationProperties bean ,因此环境属性名和 bean 属性名之间不需要完全匹配
例如属性类:
package com.lagou.pojo;


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

@Component
@ConfigurationProperties("acme.my-person.person")
public class OwnerProperties {

    public String firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Override
    public String toString() {
        return "OwnerProperties{" +
                "firstName='" + firstName + '\'' +
                '}';
    }
}
acme:
  myPerson:
    person:
      FIRST_NAME: 泰森

 六. @ConfigurationProperties vs @Value

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值