Spring 3 注解@Import、@ImportResource、@PropertySource、@Value、@ConfigurationProperties

1. @Import annotation

In general, you need to split the Spring XML bean file into multiple small files by module or category to make things easier to maintain and modularize. E.g 

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <import resource="config/customer.xml"/>
    <import resource="config/scheduler.xml"/>
 
</beans>

Spring3 JavaConfig it is equivalent to @Import function 

package com.yiibai.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {

}
  1. @Import annotation is to introduce the java class with @Configuration; ------------- This annotation helps us import multiple configuration files (may be divided by function or by business) into In a single master configuration, to avoid writing all configurations in one configuration.
  2. In spring 4.2, the @Import annotation supports importing ordinary java classes and declaring them as a bean;
package com.dxz.imports;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(DemoService.class) // 在spring 4.2之前是不不支持的
public class DemoConfig {

}

package com.dxz.imports;

public class DemoService {
    public void doSomething() {
        System.out.println("everything is all fine");
    }
}
package com.dxz.imports;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.dxz.imports");
        DemoService ds = context.getBean(DemoService.class);
        ds.doSomething();
    }
}

Two, @ImportResource annotation 

@ImportResource (value = "classpath: applicationContext1.xml") <============> Equivalent to xml configuration:  

<import resource="applicationContext1.xml" />

(1) value: String array, the content is the path of one or more xml files (relative to the classpath);

 @ImportResource(value={“classpath:applicationContext1.xml,file:applicationContext2.xml”})

(2) locations: same value attribute;

  1. @ImportResource is to introduce the spring configuration file.xml to realize the loading of xml configuration;
  2. @ImportResource: Load the corresponding xml configuration file through the locations attribute or value attribute, and it needs to be used together with the @Configuration annotation to define it as a configuration class;
  3. The configuration class introduced by @ImportResource must be scanned in the startup class;

Use @ImportResource and @Value annotations to read resource files 

package com.dxz.imports4;

public class MyDriverManager {

    public MyDriverManager(String url, String username, String password) {
        System.out.println("url : " + url);
        System.out.println("username : " + username);
        System.out.println("password : " + password);
    }
}

Create StoreConfig 

package com.dxz.imports4;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:applicationContext-democonfig2.xml")
public class StoreConfig {

    @Value("${url}")
    private String url;

    @Value("${username}")
    private String username;

    @Value("${password}")
    private String password;

    @Bean
    public MyDriverManager myDriverManager() {
        return new MyDriverManager(url, username, password);
    }
}

XML configuration (context: property-placeholder specifies the location of the resource file) applicationContext-democonfig2.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <context:property-placeholder location="classpath:config4.properties" />

    <context:component-scan base-package="com.dxz.imports4">
    </context:component-scan>

</beans>

Create resource file config4.properties 

url=127.0.0.1
username=root
password=123456

Three, @PropertySource annotation 

  1. @PropertySource annotation loads the specified property file;
  2. The attribute value annotated by @PropertySource is a String array containing the path of one or more xml files (relative to the classpath);      
  3. @PropertySource annotation is used for internal properties, with @value annotation ; ---- properties property file is in key-value format, @value ("$ {key}");

Single configuration file: 

@PropertySource(value = "classpath:spring/config.properties",ignoreResourceNotFound = true,encoding = "UTF-8")

Multiple configuration files: 

@PropertySource(value = {"classpath:spring/config.properties","classpath:spring/news.properties"})

There are two ways to use the @PropertySource annotation:

1. @PropertySource + Environment, store the value in the properties configuration file to the Spring Environment through the @PropertySource annotation. The Environment interface provides a method to read the value in the configuration file. The parameter is the key value defined in the properties file.

@Configuration
@PropertySource(value = "classpath:spring/config.properties")
public class ServiceConfiguration { 

    @Autowired 
    Environment environment; 

    public ServiceConfiguration() {
        System.out.println("ServiceConfiguration zheli");
    }
    
    @Bean
    public javax.sql.DataSource dataSource(){ 
        String user = this.environment.getProperty("ds.user");
        System.out.println(user);
        return null;
    } 
}

2、@PropertySource + @Value 

  @Component
  @PropertySource("classpath:db.properties")
  public class DBConnection {

    @Value("${DB_DRIVER_CLASS}")
    private String driverClass;

    @Value("${DB_URL}")
    private String dbUrl;

    @Value("${DB_USERNAME}")
    private String userName;

    @Value("${DB_PASSWORD}")
    private String password;

    public DBConnection(){}

    public void printDBConfigs(){
      System.out.println("Db Driver Class = " + driverClass);
      System.out.println("Db url = " + dbUrl);
      System.out.println("Db username = " + userName);
      System.out.println("Db password = " + password);
    }
  }

Four, @Value annotation 

  1. @Value injects a value for an attribute (usually used more on attributes);
  2. How to use:

      

    @Value("normal")
    private String normal; // 注入普通字符串

    @Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; // 注入操作系统属性

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; //注入表达式结果

    @Value("#{beanInject.another}")
    private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面

    @Value("classpath:com/hry/spring/configinject/config.txt")
    private Resource resourceFile; // 注入文件资源

    @Value("http://www.baidu.com")
    private Resource testUrl; // 注入URL资源

Five, @ConfigurationProperties annotation 

  1. @ConfigurationProperties can be used on classes and methods;
  2. Use on class:

       (1) Add the following configuration in application.properties:

com.example.demo.name=${aaa:hi}

com.example.demo.age=11

com.example.demo.address[0]=北京

com.example.demo.address[1]=上海

com.example.demo.address[2]=广州

com.example.demo.phone.number=1111111 

(2) Added to the class, it needs to be combined with @Component annotation, @Configuration, etc. The code is as follows:

@Component

@ConfigurationProperties(prefix = "com.example.demo")

@PropertySource(value="classpath:application.properties")

public class People {

        private String name;

        private Integer age;

        private List<String> address;

        private Phone phone;

          Note: In the above code, the ConfigurationProperties annotation is added to the People class, and the property prefix is ​​specified as com.example.demo. In this way, when Springboot is processing, it will scan all fields in the current class and perform attribute search and assembly. For example, if we configure prefix = "com.example.demo", there is a name field in the People class, and the attribute that the name field needs to match is prefix + field = com.example.demo.name.

         Then, according to the assembled properties, go to the properties file referenced by the PropertySource to find the corresponding property value. After it is found, it is automatically injected into the corresponding property of the People class, for example, the key in application.properties is the value of com.example.demo.name , Injected into the name attribute of the People class;

3. Use in methods:

     (1) The configuration in application.properties is the same as above, unchanged:     

     (2) People category;

public class People {

         private String name;

         private Integer age;

         private List<String> address;

         private Phone phone;

         // Ignore get set, just add it yourself ...

}

     (3) The declaration is made by @Bean, here we can add it to the startup class, the code is as follows:

@Configuration

@PropertySource(value="classpath:application.properties")

public class DemoApplication {

            @Bean

            @ConfigurationProperties(prefix = "com.example.demo")

            public People people() {

                      return new People();

            }

 

           public static void main(String[] args) {

                     SpringApplication.run(DemoApplication.class, args);

            }

}

Published 203 original articles · won praise 6 · views 4493

Guess you like

Origin blog.csdn.net/weixin_42073629/article/details/105401635