GVKun编程网logo

如何将@ConfigurationProperties自动连接到@Configuration?(@configurationproperty)

8

在本文中,我们将给您介绍关于如何将@ConfigurationProperties自动连接到@Configuration?的详细内容,并且为您解答@configurationproperty的相关问题

在本文中,我们将给您介绍关于如何将@ConfigurationProperties自动连接到@Configuration?的详细内容,并且为您解答@configurationproperty的相关问题,此外,我们还将为您提供关于@Configuration+@ConfigurationProperties+@EnableConfigurationProperties、@ConfigurationProperties、@ConfigurationProperties + @EnableConfigurationProperties、@ConfigurationProperties 与 @value 区别的知识。

本文目录一览:

如何将@ConfigurationProperties自动连接到@Configuration?(@configurationproperty)

如何将@ConfigurationProperties自动连接到@Configuration?(@configurationproperty)

我有一个这样定义的属性类:

@Validated@ConfigurationProperties(prefix = "plugin.httpclient")public class HttpClientProperties {   ...}

和这样的配置类:

@Configuration@EnableSchedulingpublic class HttpClientConfiguration {    private final HttpClientProperties httpClientProperties;    @Autowired    public HttpClientConfiguration(HttpClientProperties httpClientProperties) {        this.httpClientProperties = httpClientProperties;    }    ...}

启动Spring Boot应用程序时,

Parameter 0 of constructor in x.y.z.config.HttpClientConfiguration required a bean of type ''x.y.z.config.HttpClientProperties'' that could not be found.

这不是有效的用例,还是我必须以某种方式声明依赖关系?

答案1

小编典典

这是一个有效的用例,但是,HttpClientProperties由于组件扫描程序未扫描您的用户,因此未将他们接走。您可以使用来注释您HttpClientProperties@Component

@Validated@Component@ConfigurationProperties(prefix = "plugin.httpclient")public class HttpClientProperties {    // ...}

这样做的另一种方法(如StephaneNicoll所述是通过@EnableConfigurationProperties()在Spring配置类上使用注释,例如:

@EnableConfigurationProperties(HttpClientProperties.class) // This is the recommended way@EnableSchedulingpublic class HttpClientConfiguration {    // ...}

@Configuration+@ConfigurationProperties+@EnableConfigurationProperties

@Configuration+@ConfigurationProperties+@EnableConfigurationProperties

 @Configuration+@ConfigurationProperties+@EnableConfigurationProperties

 

 

最佳设计方案(现在又改板了):

Bean上面直接设置@ConfigurationProperties

//需要依赖spring-boot-configuration-processor

@ConfigurationProperties(prefix = "stu")

public class Stu {

    String name;

 

    public Stu(String name) {

        this.name = name;

    }

 

    public Stu() {

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    @Override

    public String toString() {

        return "Stu{" +

                "name=''" + name + ''\'''' +

                ''}'';

    }

}

方式一:configuration上面跟随@EnableConfigurationProperties【这种情况只有configuration里面一个Bean 】

@Configuration

@EnableConfigurationProperties

public class StuConfiguration {

    @Bean

    public Stu stu(){

        return  new Stu();

    }

}

方式二:configuration上面跟随@EnableConfigurationProperties【这种情况只有configuration里面一个Bean 】

package com.example.demo11.configuration;

import com.example.demo11.entity.Stu;

import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

//@EnableConfigurationProperties(Stu.class),如果携带class参数则有用注册Bean的能力,

//因为实现了ImportBeanDefinitionRegistrar接口,Import三插之一

//这里的Bean名称非常有意思【类型名称+全包名】

@EnableConfigurationProperties(Stu.class)

public class StuConfiguration {

    @Bean

    public Stu stu2(){

        return  new Stu();

    }

}

启动查看

@SpringBootApplication

public class Demo11Application {

    public static void main(String[] args) {

        ConfigurableApplicationContext context = SpringApplication.run(Demo11Application.class, args);

        Stu stu = context.getBean("stu-com.example.demo11.entity.Stu", Stu.class);

        System.out.println(context.getBeansOfType(Stu.class).size());

        System.out.println(stu.toString());

        context.close();

    }

 

}

@ConfigurationProperties

@ConfigurationProperties

 

功能

  将属性文件与一个Java类绑定,属性文件中的变量与Java类中的成员变量一一对应,无需完全一致。

  如需将 @ConfigurationProperties 注解的目标类添加到Spring IOC容器中,可以

  • 使用 @Component 注解目标类,这样项目启动时会自动将该类添加到容器中。
  • 使用 @EnableConfigurationProperties 间接的将 @ConfigurationProperties 注解的目标类添加到容器中。讲的详细点就是,使用 @ConfigurationProperties 注解 类A,使用 @EnableConfigurationProperties(value =  类A.class) 注解类B,那么容器在加载类B的时候,会先加载类A到容器中,实现了间接的加载。

 

源码

package org.springframework.boot.context.properties;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {

    /**
     * 属性文件中变量的前缀
     * 如果变量的全名是server.port,那么value==server。
     */
    @AliasFor("prefix")
    String value() default "";

    /**
     * 属性文件中变量的前缀
     * 如果变量的全名是server.port,那么prefix==server。
     */
    @AliasFor("value")
    String prefix() default "";

    /**
     * 是否忽略类型不匹配的错误
     */
    boolean ignoreInvalidFields() default false;

    /**
     * 是否忽略属性变量对应的字段不存在的错误
     */
    boolean ignoreUnknownFields() default true;

}

 

@ConfigurationProperties + @EnableConfigurationProperties

@ConfigurationProperties + @EnableConfigurationProperties

1、ConfigurationProperties

在类上通过@ConfigurationProperties注解声明当前类为属性读取类。

举例:

@ConfigurationProperties(prefix = "jdbc")

prefix="jdbc" 读取属性文件中,前缀为jdbc的值。

在类上定义各个属性,名称必须与属性文件中 jdbc. 后面部分一致。

需要注意的是,如果我们没有指定属性文件的地址,SpringBoot 默认读取 application.properties/application.yml  中的属性文件名。

@Data
@ConfigurationProperties(prefix = "jdbc")
class JdbcProperties {

    private String url;
    private String driverClaprivate;
    private String username;
    private String password;
}

 

2、EnableConfigurationProperties

@ConfigurationProperties 注解我们可以理解成用来把 properties 配置文件转化为 Bean 使用的,而 @EnableConfigurationProperties 注解的作用是让 @ConfigurationProperties 注解生效。

如果只配置 @ConfigurationProperties 注解,在 IOC 容器中是获取不到 properties 配置文件转化的 Bean 的。

那么我们如何获取我们使用了 @ConfigurationProperties 注解的类呢?

2.1 @Autowired 注入

@Autowired
private JdbcProperties prop;

2.2 构造函数注入

private JdbcProperties prop;
public JdbcConfig(Jdbcproperties prop){
  this.prop = prop;
}

2.3 声明有@Bean的方法参数注入

@Bean
public TestBean dataSource(JdbcProperties jdbcProperties) {
    syso(jdbcProperties.getUsername());// syso 简写
    return new TestBean;
}

通过上方三种方式,都可以在 JdbcProperties jdbcProperties 中直接拿到注入的数据。

 

@ConfigurationProperties 与 @value 区别

@ConfigurationProperties 与 @value 区别

@ConfigurationProperties 与 @value 区别

 

@ConfigurationProperties

@value

功能 批量注入配置文件中的属性 一个个指定 松散绑定 支持 不支持 SpEl 不支持 支持 JSR303 数据校验  支持  不支持 复杂类型封装 支持 不支持

 

 

 

 

  •  只是在某个业务逻辑中获取一下配置的某些值,使用 @Value

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

 

package com.hoje.springboot.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class helloController {
    @Value("${person.last-name}")
    private String name;
    @RequestMapping("/sayHello")
    public String sayHello(){
        return "Hello "+ name;
    }
}

 

 

今天关于如何将@ConfigurationProperties自动连接到@Configuration?@configurationproperty的分享就到这里,希望大家有所收获,若想了解更多关于@Configuration+@ConfigurationProperties+@EnableConfigurationProperties、@ConfigurationProperties、@ConfigurationProperties + @EnableConfigurationProperties、@ConfigurationProperties 与 @value 区别等相关知识,可以在本站进行查询。

本文标签: