SpringBoot属性注入常用注解

134 阅读1分钟

一. 注解列表

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

二. 使用1

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
@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;
    }
}
 //这里需要定义出在application文件中定义属性值得前缀信息
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    
    ......
}

注:添加@ConfigurationProperties注解后有警告:springboot 配置注释处理器未配置(编写配置文 件此时无提示) 添加spring-boot-configuration-processor后出现提示,加完依赖后通过Ctrl+F9来使之生效

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

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

三. 使用2 @ConfigurationProperties 用于注释类之外,还可以在公共@Bean 方法上使用它。当要将属 性绑定到控件之外的第三方组件时。

配置文件

another.enabled=true
another.remoteAddress=192.168.10.11

注入

@Data
public class AnotherComponent {
    private boolean enabled;
    private InetAddress remoteAddress;
}

@Configuration
public class MyService {
    @ConfigurationProperties("another")
    @Bean
    public AnotherComponent anotherComponent(){
        return new AnotherComponent();
    }
}

四. 松散绑定

acme:
 person:
  first-name: 白泽
@Data
@Component
@ConfigurationProperties("acme.person")
    public class OwnerProperties {
    private String firstName;
}
属性文件中配置说明
acme.my-project.person.first-name羊肉串模式case, 推荐使用
acme.myProject.person.firstName标准驼峰模式
acme.my_project.person.first_name下划线模式
ACME_MYPROJECT_PERSON_FIRSTNAME大写下划线,如果使用系统环境时候推荐使用