This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

preface

This section introduces the SysIndexController part of the system home page module of the Ruoyi-Admin module of Ruoyi-Vue. The interesting part of this interface is the RuoYiConfig class, which is a system configuration class. There’s an interesting annotation called ConfigurationProperties.

Obtaining system Configuration

We usually use @value for the attributes in application.yml to get the attributes stored in the corresponding configuration file

    @Value("${ruoyi.name}")
    private  String name ;
Copy the code

It is in the org. Springframework. Beans. Factory. The annotation, here under the @ Value annotation, we need to put the attribute names written to can use this property, ConfigurationProperties, which we cover next, saves us a bit of work.

ConfigurationProperties

Use on class

Here’s how the annotation is used

@Component
@ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig {    
    /** * Project name */
    private String name;
    /** * version */
    private String version;
Copy the code

And @ Value is different, it is in org. Springframework. Boot. Context. In the properties, by specifying a prefix, we can directly use ruoyi under various attributes.

# Project related configuration
ruoyi:
  # the name
  name: RuoYi
  # version
  version: 3.7. 0
  
Copy the code

You don’t even need to specify the property’s secondary name in the class, just keep the names one-to-one. @ConfigurationProperties is a good fit for batch property injection, as opposed to @Value, which can only inject a single Value. Note that @ConfigurationProperties does not support SpEL expressions.

Use it in a method

The most common use is for master-slave or read-write separation of databases. Ruoyi uses the @ConfigurationProperties annotation here.


@Configuration
public class DruidConfig
{
    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

Copy the code

Note that, as shown in the red line above, when this annotation is applied to a method, the method needs to have the @Bean annotation and the Class to which it belongs needs to have the @Configuration annotation if the binding Configuration is to be effective.