Property Injection

Injection in springboot

SpringBoot uses a global profile with a fixed profile name:

  • application.properties
  • application.yml

The role of configuration files: modify the default values of SpringBoot auto-configuration; SpringBoot is automatically configured for us at the bottom level;

Two injection methods are provided in springboot: basic property injection, object injection

Basic Property Injection @Value

Basic properties include int, String, Date, String[], List, Map, and so on.

Basic property injection: use the comment @Value("${xxx}")

@RestController
@RequestMapping("hello")
public class HelloController {
	
    @Value("${server.port}") 
    private int port;

    @Value("${str}") 
    private String str;
    
    @Value("${bir}")
    private Date bir;

    @Value("${strs}")
    private String[] strs;

    @Value("${list}")
    private List<String> list;

    @Value("#{${maps}}") // map injection value is a bit special
    private Map<String, String> maps;
    
     @GetMapping("hello")
    public String hello() {
    
    	// port = 8989
        System.out.println("port = " + port);
        // str =  zhenyu
        System.out.println("str= " + str);
        // time = Wed Dec 12 12:12:12 CST 2012
        System.out.println("time = " + bir);
        // aa
		// bb
		// cc
        for (String str : strs) {
            System.out.println(str);
        }
        // zhangsan
		// lisi
		// wangwu
        list.forEach( v -> System.out.println(v));
        // k = aa, v = xiaoyi
		// k = bb, v = xiaoer
		// k = cc, v = xiaosan
        maps.forEach((k, v) -> {
            System.out.println("k = " + k + ", v = " + v);
        });
        
        return "hello spring boot!";
        
    }
}

Application.propertiesConfiguration in:

server.port = 8989

# Attribute Injection
str = zhenyu
bir = 2012/12/12 12:12:12

strs = aa, bb, cc
list = zhangsan, lisi, wangwu
maps = {'aa':'xiaoyi', 'bb':'xiaoer', 'cc':'xiaosan'}

Object Mode Injection @ConfigurationProperties

Annotation for use of object-mode injection: @ConfigurationProperties(prefix="prefix")

@ConfigurationProperties tells SpringBoot that all properties in this class are bound in the configuration file;

  • Only if this component is a component in a container can the @ConfigurationProperties function provided by the container, so @Component is required
@ToString
@Data // necessary
@Component // @Configuration is also possible
@ConfigurationProperties(prefix = "user") // necessary
public class User {
    private String id;
    private String name;
    private Integer age;
    private Date bir;
}

Use: @Autowired in the controller to complete auto-injection;

@RestController
@RequestMapping("hello")
public class HelloController {

    @Autowired
    private User user;

    @GetMapping("hello")
    public String hello() {
        System.out.println(user); 
        // User(id=1721, name=yusael, age=20, bir=Wed Dec 12 12:12:12 CST 2012)
        return "hello spring boot!";
    }
}

Application.propertiesConfiguration in:

# Custom Object Property Injection
user.id = 1721
user.name = zhenyu
user.age = 20
user.bir = 2012/12/12 12:12:12

Note: Custom injection metadata can be built by introducing a dependency-profile processor.

  • This means that when you introduce this dependency, you will be prompted to write injection objects in the configuration file, and it won't affect you much if you don't.
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

Comparison of two injection modes

@ConfigurationProperties @Value
function Bulk Injection Properties in Configuration File Specify one by one
Loose Binding (Loose Syntax) Support I won't support it
SpEL I won't support it Support
JSR303 Data Check Support I won't support it
Complex Type Encapsulation Support I won't support it

If we just need to get a value in the configuration file in some business logic, use @Value;

If we wrote a javaBean specifically to map to the configuration file, we would use @ConfigurationProperties directly.

Injection Details

Profile Injection Value Data Check@Validated

@Component
@ConfigurationProperties(prefix = "person")
@Validated // Configuration File Injection Value Data Check
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="Literal /${key} Gets the value from environment variables, configuration files /#{SpEL}'></property>
     * <bean/>
     */

   //lastName must be in mailbox format
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

Load the specified configuration file @PropertySource

@PropertySource loads the specified configuration file;

// Load the specified profile
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
	private String lastName;
	private Integer age;
	private Boolean boss;
}

Import Spring's Configuration File@ImportResource

@ImportResource: Import Spring's profile to make the contents of the profile effective;

  • There are no Spring profiles in Spring Boot, and the profiles we write ourselves cannot be automatically identified.
    For Spring's profile to take effect, load it; @ImportResource is labeled on a configuration class;
// Import Spring's profile to make it work
@ImportResource(locations = {"classpath:beans.xml"})

Then write a configuration file for Spring:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">


    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

Profile Placeholder

Random number:

${random.uuid}
${random.value}
${random.int}
${random.long}
${random.int(10)}
${random.int[1024,65536]}

: Specify the default value in the placeholder:

person.last-name=Zhang San ${random.uuid} # random number
person.age=${random.int} # random number
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog # Specify default values
person.dog.age=15

Tags: Spring SpringBoot xml Attribute

Posted on Wed, 24 Jun 2020 22:41:17 -0400 by RonDahl